// This function is used to recover the background color of the selected button ----------- Updated by TanQilu
function recoverButtonColor(){
	$('#enableScrollStack')    .css('background-color','#DDDDDD');
	$('#grid')                 .css('background-color','#DDDDDD');
	$('#enableWindowLevelTool').css('background-color','#DDDDDD');
	$('#pan')                  .css('background-color','#DDDDDD');
	$('#zoom')                 .css('background-color','#DDDDDD');
	$('#RotateRight')          .css('background-color','#DDDDDD');
	$('#RotateLeft')           .css('background-color','#DDDDDD');
	$('#vFlip')                .css('background-color','#DDDDDD');
	$('#hFlip')                .css('background-color','#DDDDDD');
	$('#invert')               .css('background-color','#DDDDDD');
	$('#reset')                .css('background-color','#DDDDDD');
	$('#cornerMark')           .css('background-color','#DDDDDD');
	$('#enableLength')         .css('background-color','#DDDDDD');
	$('#probe')                .css('background-color','#DDDDDD');
	$('#circleroi')            .css('background-color','#DDDDDD');
	$('#rectangleroi')         .css('background-color','#DDDDDD');
	$('#angle')                .css('background-color','#DDDDDD');
	$('#ShowAnnotation')       .css('background-color','#DDDDDD');
	$('#UnShowAnnotation')     .css('background-color','#DDDDDD');
	$('#wwwc')                 .css('background-color','#DDDDDD');
	$('#synchronizer')         .css('background-color','#DDDDDD');
	$('#referenceLine')        .css('background-color','#DDDDDD');
	$('#saveImg')              .css('background-color','#DDDDDD');
	$('#WindowLevelHead')      .css('background-color','#000');
	$('#WindowLevelLung')      .css('background-color','#000');
	$('#WindowLevelChest')     .css('background-color','#000');
	$('#WindowLevelAbdomen')   .css('background-color','#000');
	$('#WindowLevelBone')      .css('background-color','#000');
	$('#resetWWWL')            .css('background-color','#000');
	$('#threeViews')           .css('background-color','#DDDDDD');
	$('#autoPlay')           .css('background-color','#DDDDDD');
	$('#getDicom')           .css('background-color','#DDDDDD');

}

// this function is used to autoplay images------------------ Updated by TanQilu
var circulation = new Function();
//this function is used to autoPlay images
function autoPlayClick(){
	recoverButtonColor();
	$('#autoPlay').css('background-color','gray');
	if(iWindowHNum*iWindowHNum != 1){
		humane.log('仅支持单窗口阅片');
		return;
	}
	if(autoPlayButtonPressed){
		$("#autoPlay span").removeClass("hy-play").addClass("hy-stop").css("color","#38c500");
		autoPlayButtonPressed = false;
		clearInterval(circulation);

		var element = $('#image00').get(0);
		wheelInstanceNum[0] = getImgIndex(element).instance;
		var seriesIndex = getImgIndex(element).series;
		circulation = setInterval(function(){
			readjustInstanceWWWL(wheelInstanceNum[0],element);
			wheelInstanceNum[0]++;
			if(wheelInstanceNum[0]>=seriesArray[seriesIndex].instance.length){
				wheelInstanceNum[0] = 0;
			}
		},100);
	} else {
		autoPlayButtonPressed = true;
		$("#autoPlay span").removeClass("hy-stop").addClass("hy-play").css("color","#505050");
		clearInterval(circulation);
	}
}

//this function is used to display MPR ------------------ Updated by TanQilu
function threeViewsClick(){
	recoverButtonColor();
	$('#threeViews').css('background-color','gray');
	if(elementChoosed=='' || iWindowHNum*iWindowVNum==1){
		elementChoosed = $('#image00').get(0);
	}

	var imgIndex = getImgIndex(elementChoosed);
	var index = imgIndex.series; //series index
	var imageOrientation = tagArray[index][0].imageOrientation;
	for(var i=1; i<tagArray[index].length; i++){
		var Xx = parseInt(tagArray[index][0].imageOrientation.split('\\')[0]);
		var Xy = parseInt(tagArray[index][0].imageOrientation.split('\\')[1]);
		var Xz = parseInt(tagArray[index][0].imageOrientation.split('\\')[2]);
		var Yx = parseInt(tagArray[index][0].imageOrientation.split('\\')[3]);
		var Yy = parseInt(tagArray[index][0].imageOrientation.split('\\')[4]);
		var Yz = parseInt(tagArray[index][0].imageOrientation.split('\\')[5]);

		if(!(Xx==1 && Xy==0 && Xz == 0 && Yx ==0 && Yy==1 && Yz==0)){
			humane.log('仅支持横截面序列');
			return;
		}

		if(tagArray[index][i].imageOrientation != imageOrientation){
			humane.log('影像序列不统一');
			return;
		}
	}

	$('#modalProgressGlobal').modal('show');

	// to record the the width and height of current window, then empty it
	var imageElement = $('#'+elementChoosed.id).parent();

	var eleRowIndex = elementChoosed.id.substring(
		elementChoosed.id.indexOf('image')+5,
		elementChoosed.id.indexOf('image')+6);
	var eleColumnIndex = elementChoosed.id.substring(
		elementChoosed.id.indexOf('image')+6);
	eleRowIndex = parseInt(eleRowIndex);
	eleColumnIndex = parseInt(eleColumnIndex);

	var subViewsNum = eleRowIndex*iWindowVNum+eleColumnIndex;

	var localWidth = imageElement.width();
	var localHeight = imageElement.height();

	imageElement.empty();
	imageElement.css('display', 'inline-block');
	imageElement.css('height',(localHeight-5).toString());

	$('#toolbar-function').css('display','none');
	$('#toolbar-function-simple').css('display','block');
	$('#mrtopleft').css('display','none');

	// generate the structure of four sub-views
	var cnt = 0;
	var divContent = '<table id="subViews" style="width: 100%; height: 100%; border: 1px solid #D5D5D5; background-color: #000;">';
	for(var i=0; i<2; i++){
		divContent += '<tr height="50%";>';
		for(var j=0; j<2; j++){
			divContent += '<td style="width: 50%; border:1px solid #454444;">';
			divContent +='<div style="width:'
				+ 100
				+ '%;'
				+ 'height:'
				+ 100
				+ '%'
				+ ';position:relative;display:inline-block;color:white;"'
				+ '>';
			divContent +='<div id="sub'+subViewsNum.toString()+cnt.toString()+'"style="position: relative;width: 100%;height: 100%;"></div></div></td>';
			cnt++;
		}
		divContent += '</tr>';
	}
	divContent += '</table>';
	imageElement.get(0).innerHTML = divContent;

	for(var i=0; i<4; i++){
		var element = $('#sub'+subViewsNum.toString()+i.toString()).get(0);
		var eleWidth = $('#'+element.id).width();
		cornerstone.enable(element);
		element.style.width = eleWidth+'px';
	}

	// generate the information div to display current image number
	var info1 = $('<div></div>');
	info1.attr('id','info'+subViewsNum.toString()+'1');
	info1.attr('style','position:absolute; color:white; bottom:6px; left:6px; width:100px; height:20px;');
	info1.appendTo($('#sub'+subViewsNum.toString()+'1'));

	var info2 = $('<div></div>');
	info2.attr('id','info'+subViewsNum.toString()+'2');
	info2.attr('style','position:absolute; color:white; bottom:6px; left:6px; width:100px; height:20px;');
	info2.appendTo($('#sub'+subViewsNum.toString()+'2'));

	var info3 = $('<div></div>');
	info3.attr('id','info'+subViewsNum.toString()+'3');
	info3.attr('style','position:absolute; color:white; bottom:6px; left:6px; width:100px; height:20px;');
	info3.appendTo($('#sub'+subViewsNum.toString()+'3'));

	// get all the images of current series
	var imageIDs = [];
	var imageData =[]; // all the pixel datas of this series

	loadImages(hosturl, serverURL, studyUID, seriesArray[index], imageIDs, imageType);
	for(var i=0; i<seriesArray[index].instance.length; i++){
		cornerstone.loadAndCacheImage(imageIDs[i]).then(function(image){
			var pixelData = image.getPixelData();
			var idStart = image.imageId.indexOf('object=')+7;
			var idEnd = image.imageId.indexOf('&rows');
			var objectID = image.imageId.substring(idStart,idEnd);
			var pixels =
			{
				objectID: objectID,
				pixelData: pixelData
			}
			imageData.push(pixels);

			// since all the series have been loaded, next step is to show the MPR
			if(imageData.length == seriesArray[index].instance.length){
				var imageIdx = getImgIndex(undefined,image);
				var scaleV = parseFloat(thickness[imageIdx.series]);
				var scaleH = parseFloat(tagArray[imageIdx.series][imageIdx.instance].pixelSpacing.split('\\')[0]);
				var stretchScale = scaleV/scaleH;
				// sort the image series
				var tempArray = [];
				for(var i=0; i<imageData.length; i++){
					for(var j=0; j<imageData.length; j++){
						if(imageData[j].objectID == seriesArray[index].instance[i].sopIUID){
							tempArray.push(imageData[j]);
							break;
						}
					}
				}
				imageData = tempArray;

				// build the image region which is to be showed; it is a matrix
				var width = image.width;
				var height = image.height;

				/*--------------------------------------------------------------------------------
				 * generate image in the canvas of sub0
				 ---------------------------------------------------------------------------------*/
				var canvas0 = cornerstone.getEnabledElement($('#sub'+subViewsNum.toString()+'0').get(0)).canvas;
				var canvas0Width = canvas0.width;
				var canvas0Height = canvas0.height;
				canvas0.width = width;
				canvas0.height = height;
				var context0 = canvas0.getContext('2d');
				var pixelDisp0 = context0.createImageData(width,height);

				// get each pixel data to be showed
				for(var i=0; i<=(width*height-1)*4; i+=4){
					pixelDisp0.data[i+0] = imageData[parseInt(imageData.length/2)].pixelData[i+0];
					pixelDisp0.data[i+1] = imageData[parseInt(imageData.length/2)].pixelData[i+1];
					pixelDisp0.data[i+2] = imageData[parseInt(imageData.length/2)].pixelData[i+2];
					pixelDisp0.data[i+3] = imageData[parseInt(imageData.length/2)].pixelData[i+3];
				}
				context0.putImageData(pixelDisp0,0,0);

				// change the width and height scale of imageData
				var dataURL0 = canvas0.toDataURL();
				var img0 = new Image();
				img0.src = dataURL0;
				canvas0.width = canvas0Width;
				canvas0.height = canvas0Height;

				/*--------------------------------------------------------------------------------
				 * generate image in the canvas of sub1
				 ---------------------------------------------------------------------------------*/
				var canvas1 = cornerstone.getEnabledElement($('#sub'+subViewsNum.toString()+'1').get(0)).canvas;
				var canvas1Width = canvas1.width;
				var canvas1Height = canvas1.height;
				canvas1.width = width;
				canvas1.height = height;
				var context1 = canvas1.getContext('2d');
				var pixelDisp1 = new Array(imageData.length);

				// get each pixel data to be showed
				for(var slice=0; slice<imageData.length; slice++){
					pixelDisp1[slice] = context1.createImageData(width,height);
					for(var i=0; i<=(width*height-1)*4; i+=4){
						pixelDisp1[slice].data[i+0] = imageData[slice].pixelData[i+0];
						pixelDisp1[slice].data[i+1] = imageData[slice].pixelData[i+1];
						pixelDisp1[slice].data[i+2] = imageData[slice].pixelData[i+2];
						pixelDisp1[slice].data[i+3] = imageData[slice].pixelData[i+3];
					}
				}
				context1.putImageData(pixelDisp1[0],0,0);

				// change the width and height scale of imageData
				var dataURL1 = canvas1.toDataURL();
				var img1 = new Image();
				img1.src = dataURL1;
				canvas1.width = canvas1Width;
				canvas1.height = canvas1Height;

				/*-----------------------------------------------------------------------------------------
				 * generate image in the canvas of sub2
				 ------------------------------------------------------------------------------------------*/
				var canvas2 = cornerstone.getEnabledElement($('#sub'+subViewsNum.toString()+'2').get(0)).canvas;
				var canvas2Width = canvas2.width;
				var canvas2Height = canvas2.height;
				canvas2.width = height;
				canvas2.height = imageData.length;
				var context2 = canvas2.getContext('2d');
				var pixelDisp2 = new Array(imageData.length);

				// get each pixel data to be showed
				for(var slice=0; slice<width; slice++){
					var pixIndex = 0;
					var startIdx = slice*4;
					var endIdx = (slice+width*(height-1))*4;
					pixelDisp2[slice] = context2.createImageData(height,imageData.length);
					for(var i=0; i<imageData.length; i++){
						for(var j=startIdx; j<=endIdx; j+=width*4){
							pixelDisp2[slice].data[pixIndex+0] = imageData[i].pixelData[j+0];
							pixelDisp2[slice].data[pixIndex+1] = imageData[i].pixelData[j+1];
							pixelDisp2[slice].data[pixIndex+2] = imageData[i].pixelData[j+2];
							pixelDisp2[slice].data[pixIndex+3] = imageData[i].pixelData[j+3];

							pixIndex += 4;
						}
					}
				}
				context2.putImageData(pixelDisp2[parseInt(width/2)],0,0);

				// change the width and height scale of imageData
				var dataURL2 = canvas2.toDataURL();
				var img2 = new Image();
				img2.src = dataURL2;
				canvas2.width = canvas2Width;
				canvas2.height = canvas2Height;

				/*----------------------------------------------------------------------------------------
				 * generate image in the canvas of sub3
				 -----------------------------------------------------------------------------------------*/
				var canvas3 = cornerstone.getEnabledElement($('#sub'+subViewsNum.toString()+'3').get(0)).canvas;
				var canvas3Width = canvas3.width;
				var canvas3Height = canvas3.height;
				canvas3.width = width;
				canvas3.height = imageData.length;
				var context3 = canvas3.getContext('2d');
				var pixelDisp3 = new Array(imageData.length);

				// get each pixel data to be showed
				for( var slice=0; slice<height; slice++){
					var pixIndex = 0;
					var startIdx = (slice*width)*4;
					var endIdx = ((slice+1)*width-1)*4;
					pixelDisp3[slice] = context3.createImageData(width,imageData.length);
					for(var i=0; i<imageData.length; i++){
						for(var j=startIdx; j<=endIdx; j+=4){
							pixelDisp3[slice].data[pixIndex+0] = imageData[i].pixelData[j+0];
							pixelDisp3[slice].data[pixIndex+1] = imageData[i].pixelData[j+1];
							pixelDisp3[slice].data[pixIndex+2] = imageData[i].pixelData[j+2];
							pixelDisp3[slice].data[pixIndex+3] = imageData[i].pixelData[j+3];

							pixIndex += 4;
						}
					}
				}
				context3.putImageData(pixelDisp3[parseInt(height/2)],0,0);

				// change the width and height scale of imageData
				var dataURL3 = canvas3.toDataURL();
				var img3 = new Image();
				img3.src = dataURL3;
				canvas3.width = canvas3Width;
				canvas3.height = canvas3Height;

				// to bind the mouse wheel event
				$('#sub'+subViewsNum.toString()+'1').on('mousewheel DOMMouseScroll',mouseWheel);
				$('#sub'+subViewsNum.toString()+'2').on('mousewheel DOMMouseScroll',mouseWheel);
				$('#sub'+subViewsNum.toString()+'3').on('mousewheel DOMMouseScroll',mouseWheel);

				windowResize();
				window.addEventListener('resize', windowResize,false);

				// this function is used to adjust the table to let it fit the whole page
				function windowResize(){
					if($('#sub'+subViewsNum.toString()+'0').get(0) == undefined){ // when this button is off
						return;
					}

					var localWidth = imageElement.width();
					var localHeight = imageElement.height();
					$('#imageContainer').parent().css('height','100%');
					$('#imageContainer').css('height','100%');
					$('#tableViews').css('height','99.9%');

					for(var i=0; i<4; i++){
						var imgCanvas = $('#sub'+subViewsNum.toString()+i.toString()).find('canvas');
						imgCanvas.get(0).height = Math.floor(localHeight/2-6);
						imgCanvas.get(0).width = Math.floor(localWidth/2-6);
						imgCanvas.css('height',Math.floor(localHeight/2-6).toString()+'px');
						imgCanvas.css('width',Math.floor(localWidth/2-6).toString()+'px');
					}

					// draw images in all sub-viewports
					drawImage0();
					drawImage1();
					drawImage2();
					drawImage3();

					$('#modalProgressGlobal').modal('hide');
				}

				// fill and fit the sub0 screen
				function drawImage0(){
					canvas0Width = canvas0.width;
					canvas0Height = canvas0.height;
					if(canvas0Height/height > canvas0Width/width){
						context0.drawImage(img0,
							0,
							(canvas0Height-parseInt(height*canvas0Width/width))/2,
							canvas0Width,
							parseInt(height*canvas0Width/width));
					} else {
						context0.drawImage(img0,
							(canvas0Width-parseInt(width*canvas0Height/height))/2,
							0,
							parseInt(width*canvas0Height/height),
							canvas0Height);
					}
				}

				// fill and fit the sub1 screen
				var drawParameter1 = {};
				function drawImage1(){
					canvas1Width = canvas1.width;
					canvas1Height = canvas1.height;
					var draw =
					{
						startX: 0,
						startY: 0,
						width:  0,
						height: 0
					};
					if(canvas1Height/height > canvas1Width/width){
						draw.startX = 0;
						draw.startY = (canvas1Height-parseInt(height*canvas1Width/width))/2;
						draw.width = canvas1Width;
						draw.height = parseInt(height*canvas1Width/width);
					} else {
						draw.startX = (canvas1Width-parseInt(width*canvas1Height/height))/2;
						draw.startY = 0;
						draw.width = parseInt(width*canvas1Height/height);
						draw.height = canvas1Height;
					}
					context1.drawImage(img1,draw.startX,draw.startY,draw.width,draw.height);
					drawParameter1 = draw;

					var displayText = 'Img: ' + (imgIndex1+1 || 1).toString() + '/' + imageData.length.toString();
					info1[0].innerHTML = displayText;
				}

				// fill and fit the sub2 screen
				var drawParameter2 = {};
				function drawImage2(){
					canvas2Width = canvas2.width;
					canvas2Height = canvas2.height;
					var draw =
					{
						startX: 0,
						startY: 0,
						width:  0,
						height: 0
					};
					if(canvas2Height/((imageData.length)*stretchScale) > canvas2Width/width){
						draw.startX = 0;
						draw.startY = (canvas2Height-parseInt((imageData.length)*stretchScale*canvas2Width/width))/2;
						draw.width = canvas2Width;
						draw.height = parseInt((imageData.length)*stretchScale*canvas2Width/width);
					} else {
						draw.startX = (canvas2Width-parseInt(width*canvas2Height/((imageData.length)*stretchScale)))/2;
						draw.startY = 0;
						draw.width = parseInt(width*canvas2Height/((imageData.length)*stretchScale));
						draw.height = canvas2Height;
					}
					context2.drawImage(img2,draw.startX,draw.startY,draw.width,draw.height);
					drawParameter2 = draw; // export

					var displayText = 'Img: ' + (imgIndex2+1 || parseInt(width/2)+1).toString() + '/' + width.toString();
					info2[0].innerHTML = displayText;
				}

				// fill and fit the sub3 screen
				var drawParameter3 = {};
				function drawImage3(){
					canvas3Width = canvas3.width;
					canvas3Height = canvas3.height;
					var draw =
					{
						startX: 0,
						startY: 0,
						width:  0,
						height: 0
					};
					if(canvas3Height/((imageData.length)*stretchScale) > canvas3Width/width){
						draw.startX = 0;
						draw.startY = (canvas3Height-parseInt((imageData.length)*stretchScale*canvas3Width/width))/2;
						draw.width = canvas3Width;
						draw.height = parseInt((imageData.length)*stretchScale*canvas3Width/width);
					} else {
						draw.startX = (canvas3Width-parseInt(width*canvas3Height/((imageData.length)*stretchScale)))/2;
						draw.startY = 0;
						draw.width = parseInt(width*canvas3Height/((imageData.length)*stretchScale));
						draw.height = canvas3Height;
					}
					context3.drawImage(img3,draw.startX,draw.startY,draw.width,draw.height);
					drawParameter3 = draw; // export

					var displayText = 'Img: ' + (imgIndex3+1 || parseInt(height/2)+1).toString() + '/' + height.toString();
					info3[0].innerHTML = displayText;
				}

				var imgIndex1 = 0;
				var imgIndex2 = parseInt(width/2);
				var imgIndex3 = parseInt(height/2);

				// mouseWheel event of "threeViewers" button
				function mouseWheel(e){
					var element = e.currentTarget;

					if(element.id == 'sub'+subViewsNum.toString()+'1'){
						if(e.originalEvent.deltaY>0){
							imgIndex1++;
							imgIndex1 = imgIndex1<imageData.length? imgIndex1 : imageData.length-1;
						} else if(e.originalEvent.deltaY<0){
							imgIndex1--;
							imgIndex1 = imgIndex1>-1? imgIndex1 : 0;
						}
						// to invoke the imageData
						canvas1.width = width;
						canvas1.height = height;
						context1.putImageData(pixelDisp1[imgIndex1],0,0);

						//change the width and height scale of imageData
						img1.src = canvas1.toDataURL();
						canvas1.width = canvas1Width;
						canvas1.height = canvas1Height;

						//fill and fit the sub1 screen
						drawImage1();

						// draw reference line in sub2
						drawImage2();
						context2.beginPath();
						context2.moveTo(drawParameter2.startX,
							drawParameter2.startY+drawParameter2.height*(imgIndex1+0.5)/imageData.length);
						context2.lineTo(drawParameter2.startX+drawParameter2.width-1,
							drawParameter2.startY+drawParameter2.height*(imgIndex1+0.5)/imageData.length);
						context2.strokeStyle = 'yellow';
						context2.lineWidth = 2;
						context2.stroke();

						// draw reference line in sub3
						drawImage3();
						context3.beginPath();
						context3.moveTo(drawParameter3.startX,
							drawParameter3.startY+drawParameter3.height*(imgIndex1+0.5)/imageData.length);
						context3.lineTo(drawParameter3.startX+drawParameter3.width-1,
							drawParameter3.startY+drawParameter3.height*(imgIndex1+0.5)/imageData.length);
						context3.strokeStyle = 'yellow';
						context3.lineWidth = 2;
						context3.stroke();

					}
					if(element.id == 'sub'+subViewsNum.toString()+'2'){
						if(e.originalEvent.deltaY>0){
							imgIndex2++;
							imgIndex2 = imgIndex2<width? imgIndex2 : width-1;
						} else if(e.originalEvent.deltaY<0){
							imgIndex2--;
							imgIndex2 = imgIndex2>-1? imgIndex2 : 0;
						}
						// to invoke the imageData
						canvas2.width = width;
						canvas2.height = imageData.length;
						context2.putImageData(pixelDisp2[imgIndex2],0,0);

						// change the width and height scale of imageData
						img2.src = canvas2.toDataURL();
						canvas2.width = canvas2Width;
						canvas2.height = canvas2Height;

						// fill and fit the sub2 screen
						drawImage2();

						// draw reference line in sub1
						drawImage1();
						context1.beginPath();
						context1.moveTo(drawParameter1.startX+drawParameter1.width*(imgIndex2+0.5)/width,
							drawParameter1.startY);
						context1.lineTo(drawParameter1.startX+drawParameter1.width*(imgIndex2+0.5)/width,
							drawParameter1.startY+drawParameter1.height-1);
						context1.strokeStyle = 'yellow';
						context1.lineWidth = 2;
						context1.stroke();

						// draw reference line in sub3
						drawImage3();
						context3.beginPath();
						context3.moveTo(drawParameter3.startX+drawParameter3.width*(imgIndex2+0.5)/width,
							drawParameter3.startY);
						context3.lineTo(drawParameter3.startX+drawParameter3.width*(imgIndex2+0.5)/height,
							drawParameter3.startY+drawParameter3.height-1);
						context3.strokeStyle = 'yellow';
						context3.lineWidth = 2;
						context3.stroke();
					}
					if(element.id == 'sub'+subViewsNum.toString()+'3'){
						if(e.originalEvent.deltaY>0){
							imgIndex3++;
							imgIndex3 = imgIndex3<height? imgIndex3 : height-1;
						} else if(e.originalEvent.deltaY<0){
							imgIndex3--;
							imgIndex3 = imgIndex3>-1? imgIndex3 : 0;
						}
						// to invoke the imageData
						canvas3.width = width;
						canvas3.height = imageData.length;
						context3.putImageData(pixelDisp3[imgIndex3],0,0);

						// change the width and height scale of imageData
						img3.src = canvas3.toDataURL();
						canvas3.width = canvas3Width;
						canvas3.height = canvas3Height;

						// fill and fit the sub3 screen
						drawImage3();

						// draw reference line in sub1
						drawImage1();
						context1.beginPath();
						context1.moveTo(drawParameter1.startX,
							drawParameter1.startY+drawParameter1.height*(imgIndex3+0.5)/height);
						context1.lineTo(drawParameter1.startX+drawParameter1.width-1,
							drawParameter1.startY+drawParameter1.height*(imgIndex3+0.5)/height);
						context1.strokeStyle = 'yellow';
						context1.lineWidth = 2;
						context1.stroke();

						// draw reference line in sub2
						drawImage2();
						context2.beginPath();
						context2.moveTo(drawParameter2.startX+drawParameter2.width*(imgIndex3+0.5)/height,
							drawParameter2.startY);
						context2.lineTo(drawParameter2.startX+drawParameter2.width*(imgIndex3+0.5)/height,
							drawParameter2.startY+drawParameter2.height-1);
						context2.strokeStyle = 'yellow';
						context2.lineWidth = 2;
						context2.stroke();
					}
				}
			}
		});
	}
}

// display or close the corner mark of each viewport -------------- Updated by TanQilu
function cornerMarkClick(){
	console.log("cornermark");
	recoverButtonColor();
	$('#cornerMark').css('background-color','gray');

	if(dis == false){
		dis = true;
	}else{
		dis = false;
	}
	humane.log("显示/隐藏角标",{timeout : 2000});
	if (viewportNum == 0) {
		for(var i=0; i<=sort; i++){
			$("#mrtopright" + i).toggle();
			$("#mrbottomright" + i).toggle();
			$("#mrbottomleft" + i).toggle();
		}
	} else {
		for(var i=0; i<=viewportNum; i++){
			$("#mrtopright" + i).toggle();
			$("#mrbottomright" + i).toggle();
			$("#mrbottomleft" + i).toggle();
		}
	}
}

// recover the window level and window width when modified by the five buttons on the left -------------- Updated by TanQilu
$('#resetWWWL').click(function(){
	humane.log("重置 窗宽/窗位",{timeout : 2000});
	recoverButtonColor();
	$('#resetWWWL').css('background-color','gray');
	$('#imageContainer').removeClass('adjust');

	if(contrastButtonPressed == false){
		return;
	}
	for(var i=0; i<iWindowHNum; i++){
		for(var j=0; j<iWindowVNum; j++){
			var element = $('#image'+i.toString()+j.toString()).get(0);
			var curElement = cornerstone.getEnabledElement(element);

			var eleIndex = 0;
			if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
				eleIndex = parseInt(sort);
			} else {
				eleIndex = i*iWindowVNum+j;
			}

			if(eleIndex <= viewportNum || iWindowVNum*iWindowHNum==1){
				var eleImgIndex = 0;
				if(iWindowHNum*iWindowVNum==1){
					eleImgIndex = sort;
				} else {
					eleImgIndex = loadedIndex[eleIndex]==-1 ? eleIndex : loadedIndex[eleIndex];
				}
				var curImageIDs = [];
				loadImages(hosturl, serverURL, studyUID, seriesArray[eleImgIndex], curImageIDs,imageType);

				var instanceNum = getImgIndex(element).instance;
				curImageIDs[instanceNum] = curImageIDs[instanceNum] +
					'&windowWidth=' + initialWW[eleIndex].toString() +
					'&windowCenter=' + initialWL[eleIndex].toString();
				cornerstone.loadAndCacheImage(curImageIDs[instanceNum]).then( function(image){
					cornerstone.displayImage(element,image);
					var viewport = curElement.viewport;
					viewport.voi.windowCenter = image.windowCenter;
					viewport.voi.windowWidth = image.windowWidth;
					cornerstone.setViewport(element,viewport);
					triggerResize();
				});

				globalWW[eleIndex] = initialWW[eleIndex];
				globalWL[eleIndex] = initialWL[eleIndex];
			}
		}
	}

	cornerstoneTools.wwwc.deactivate(element,1);
});

// build/remove the connection of synchronizers -------------- Updated by TanQilu
function synchronizerClick(){
	console.log("synchronizer");
	humane.log("建立/解除 序列关联");
	recoverButtonColor();
	$('#synchronizer').css('background-color','gray');

	if(synchrSwitch){
		synchrSwitch = false;
		$("#synchronizer span").removeClass("hy-jiesuo").addClass("hy-suoding").css("color","#38c500");
	} else {
		synchrSwitch = true;
		$("#synchronizer span").removeClass("hy-suoding").addClass("hy-jiesuo").css("color","#505050");
	}
}

// turn on/off the reference lines -------------- Updated by TanQilu
function referenceLineClick(){
	humane.log( "点击某一子窗口 开启/关闭定位线" );
	recoverButtonColor();
	$('#referenceLine').css('background-color','gray');
	// 如果是关闭此按钮，则刷新所有图像后退出，否则继续执行后续代码
	if(referenceLineButtonPressed === false) {
		referenceLineButtonPressed = true;
	} else {
		referenceLineButtonPressed = false;
		updateAllImageDisplayed();
		return;
	}

	// 这一段是复制的“synchronizer”里面的代码，目的是关闭关联
	for( var i=0; i<iWindowHNum; i++){
		for( var j=0; j<iWindowVNum; j++){
			if(i*iWindowVNum+j >= loadedIndex.length){
				break;
			}
			var curElement = $('#image'+i.toString()+j.toString()).get(0);
			var curSeriesIndex = loadedIndex[i*iWindowVNum+j] == -1 ? i*iWindowVNum+j : loadedIndex[i*iWindowVNum+j];
			var curGroupIndex = groupIndex[curSeriesIndex];

			synchronizers[curGroupIndex].remove(curElement);
		}
	}
	synchrSwitch = false;

	var element = elementChoosed == '' ? $('#image00').get(0) : elementChoosed;
	drawReferenceLine(element);
}

// Hua
// 取Study对象
function loadStudy(hosturl, patId, studyUID, dcmurl, serverurl) {
	var data = {
		patientid : patId,
		studyid : studyUID,
		dcmURL : dcmurl
	};
	lmViewer.srv.service_series_getseries(data,function(data){
		console.log("[imageShow|service_series_getseries|success]---"+JSON.stringify(data,null,4));
		var message = data.message;
		iSeriesNum = message.length;

		for(var i = 0; i < iSeriesNum; i++){
			tagArray[i] = new Array();
		}

		if (iSeriesNum > 0) {
			series = message;
			totalSeries = iSeriesNum;

			for (var i = 0; i < iSeriesNum; i++) {

				// 取序列下的影像
				loadInstances(hosturl, patId, studyUID,
					series[i].seriesIUID, dcmurl, serverurl, i);

			}
		} else {
			humane.log("影像服务器连接错误。Cannot connect server to get the study.");
			$('#modalProgressGlobal').modal('hide');
		}
	},function(data){
		humane.log("影像服务器连接错误。Cannot connect server to get the study.");
		$('#modalProgressGlobal').modal('hide');
	})
/*	$.ajax({
		url : hosturl + '/imagecloud/service/series/getseries',
		type : 'get',
		data : {
			patientid : patId,
			studyid : studyUID,
			dcmURL : dcmurl
		},
		dataType : 'json',
		success : function(data) {
			var message = JSON.parse(data.message);
			iSeriesNum = message.length;

			for(var i = 0; i < iSeriesNum; i++){
				tagArray[i] = new Array();
			}

			if (iSeriesNum > 0) {
				series = message;
				totalSeries = iSeriesNum;

				for (var i = 0; i < iSeriesNum; i++) {

					// 取序列下的影像
					loadInstances(hosturl, patId, studyUID,
						series[i].seriesIUID, dcmurl, serverurl, i);

				}
			} else {
				humane.log("影像服务器连接错误。Cannot connect server to get the study.");
				$('#modalProgressGlobal').modal('hide');
			}

		},
		error : function(data) {
			humane.log("影像服务器连接错误。Cannot connect server to get the study.");
			$('#modalProgressGlobal').modal('hide');
		}
	});*/
}

// 取序列影像
function loadInstances(hosturl, patId, studyUID, seriesUID, dcmurl, serverurl, index) {
	var data = {
		hostURL:hosturl,
		patientid:patId,
		studyid:studyUID,
		seriesid:seriesUID,
		dcmURL:dcmurl,
		serverURL:serverurl
	};
	lmViewer.srv.service_instances_getinstances(data,function(data){
		console.log("[imageShow|service_instances_getinstances|success]---"+JSON.stringify(data,null,4));
		var instances = data.message;
		var objmo = new Object();
		var ob = {
			seriesUID : seriesUID,
			instance : instances
		};

		locations[index] = instances[0].sliceLocation;
		thickness[index] = instances[0].sliceThickness;
		orientation[index] = instances[0].imgOrient;

		// Save series
		seriesArray.push(ob);
		loaded.push(1);
		loadedIndex.push(-1);

		var instanceImgs = ob.instance;
		var instanceLength = ob.instance.length;

		for(var i = 0; i < instanceLength; i++){
			var tagElement = new Object();
			tagArray[index].push(tagElement);
		};

		initDicomViewer();
	},function(data){
		humane.log(
			"影像服务器连接错误。Cannot connect server to get the series information.",
			{
				timeout : 4000,
				clickToClose : true,
				addnCls : 'humane-error'
			});
		$('#modalProgressGlobal').modal('hide');
	});

/*	$.ajax({
		url : hosturl + '/imagecloud/service/instances/getinstances',
		type : 'get',
		data : {
			hostURL : hosturl,
			patientid : patId,
			studyid : studyUID,
			seriesid : seriesUID,
			dcmURL : dcmurl,
			serverURL : serverurl
		},

		dataType : 'json',
		success : function(data) {
			var instances = JSON.parse(data.message);
			var objmo = new Object();
			var ob = {
				seriesUID : seriesUID,
				instance : instances
			};

			locations[index] = instances[0].sliceLocation;
			thickness[index] = instances[0].sliceThickness;
			orientation[index] = instances[0].imgOrient;

			// Save series
			seriesArray.push(ob);
			loaded.push(1);
			loadedIndex.push(-1);

			var instanceImgs = ob.instance;
			var instanceLength = ob.instance.length;

			for(var i = 0; i < instanceLength; i++){
				var tagElement = new Object();
				tagArray[index].push(tagElement);
			};

			initDicomViewer();
		},
		error : function(data) {
			humane.log(
				"影像服务器连接错误。Cannot connect server to get the series information.",
				{
					timeout : 4000,
					clickToClose : true,
					addnCls : 'humane-error'
				});
			$('#modalProgressGlobal').modal('hide');
		}
	});*/

}

// load the tags of all the instances in the current study
function loadTagInfos(hosturl,studyUID){
	var data = {
		studyIuid:studyUID
	};
	lmViewer.srv.GetFileMetaInfoServlet(data,function(data){
		console.log("[imageShow|GetFileMetaInfoServlet|success]---"+JSON.stringify(data,null,4));
		tags = data;
	},function(data){
		humane.log("获取服务器数据错误！",{
			timeout: 4000,
			clickToClose: true,
			addnCls: 'humane-error'
		});
		$('#modalProgressGlobal').modal('hide');
		});

/*	$.ajax({
		url: hosturl + '/imagecloud/GetFileMetaInfoServlet',
		type: 'post',
		data: {
			studyIuid: studyUID
		},
		dataType : 'json',
		success: function(data){
			tags = data;
		},
		error: function(data){
			humane.log("获取服务器数据错误！",{
				timeout: 4000,
				clickToClose: true,
				addnCls: 'humane-error'
			});
			$('#modalProgressGlobal').modal('hide');
		}
	});*/
}


// 准备显示
function initDicomViewer() {
	!function($) {

		// is loaded completely
		var itotal = 0;
		for (var i = 0; i < seriesArray.length; i++) {
			itotal = itotal + loaded[i];

		}

		if (itotal != totalSeries) {
			return;
		}
		// 对序列排序
		sortSeries();

		// hide the buttons displayed in vertical line on the left side when the images modality is not CT
		if(series[0].modality != "CT" || isMobile){
			document.getElementById('WindowLevelHead').style.display = "none";
			document.getElementById('WindowLevelLung').style.display = "none";
			document.getElementById('WindowLevelChest').style.display = "none";
			document.getElementById('WindowLevelAbdomen').style.display = "none";
			document.getElementById('WindowLevelBone').style.display = "none";
			document.getElementById('resetWWWL').style.display = "none";
		}

		// get the global variable "maxSeriesNum"
		maxSeriesNum = seriesArray[0].instance.length;
		for(var i = 0; i < iSeriesNum; i++){
			maxSeriesNum = maxSeriesNum > seriesArray[i].instance.length ? maxSeriesNum : seriesArray[i].instance.length;
		}

		// display div
		$('#content').show();

		// sort the "tags" array, in order to unify the structure
		// of "tagArray" and "seriesArray" ----------------------------------Updated by TanQilu
		sortTags();

		// distinguish into groups
		distinguishGroup();

		//renumber the instances of every series -----------------------------------Updated by TanQilu
		renumberInstances();

		// 取序列列表（显示tab1）
		generateSeriesList(hosturl, serverURL, studyUID, seriesArray, series);

		// 设置进度条 显示影像
		showSeries(iWindowVNum, iWindowHNum);

	}(jQuery);
}

// load the parameter from querystring
function getParameter(queryString, parameterName) {
	// Add "=" to the parameter name (i.e. parameterName=value);
	var parameterName = parameterName + "=";
	if (queryString.length > 0) {
		// Find the beginning of the string
		var begin = queryString.indexOf(parameterName);
		if (begin != -1) {
			// Add the length (integer) to the beginning
			begin += parameterName.length;
			var end = queryString.indexOf("&", begin);
			if (end == -1) {
				end = queryString.length;
			}
			return unescape(queryString.substring(begin, end));
		}

		return null;
	}
}

// 影像全路径（通过该路径下载影响）
function loadImages(hosturl, serverURL, studyUID, series, imagesid, type) {
	var insNum = series.instance.length;

	if (type == "" || type == null) {
		for (var i = 0; i < insNum; i++) {
			var imageURL = "";

			if (imageType == "dicom" || imageType == "dicom#") {
				imageURL = imageURL + "dicomweb:" + hosturl + '/imagecloud/read?'
					+ 'serverURL=' + serverURL + '/wado&' + 'study='
					+ studyUID + '&series=' + series.seriesUID + '&object='
					+ series.instance[i].sopIUID
					+ '&contentType=application%2Fdicom';
			}
			else if (imageType == "png" || imageType == "png#") {
				imageURL = imageURL + hosturl + '/imagecloud/read?' + 'serverURL='
					+ serverURL + '/wado&' + 'study=' + studyUID
					+ '&series=' + series.seriesUID + '&object='
					+ series.instance[i].sopIUID + '&contentType=image/png';
			}
			else {
				imageURL = imageURL + hosturl + '/imagecloud/read?' + 'serverURL='
					+ serverURL + '/wado&study=' + studyUID
					+ '&series=' + series.seriesUID + '&object='
					+ series.instance[i].sopIUID;
			}
			imagesid.push(imageURL);
		}
	} else {
		for (var i = 0; i < insNum; i++) {
			var imageURL = "";

			if (type == "dicom" || type == "dicom#") {
				imageURL = imageURL + "dicomweb:" + hosturl + '/imagecloud/read?'
					+ 'serverURL=' + serverURL + '/wado&' + 'study='
					+ studyUID + '&series=' + series.seriesUID + '&object='
					+ series.instance[i].sopIUID + '&rows=512'
					+ '&contentType=application%2Fdicom';
			} else if (type == "jpg" || type == "jpg#") {
				imageURL = imageURL + hosturl + '/imagecloud/read?' + 'serverURL='
					+ serverURL + '/wado&' + 'study=' + studyUID
					+ '&series=' + series.seriesUID + '&object='
					+ series.instance[i].sopIUID + '&rows=512';
			} else if (type == "png" || type == "png#") {
				imageURL = imageURL + hosturl + '/imagecloud/read?' + 'serverURL='
					+ serverURL + '/wado&' + 'study=' + studyUID
					+ '&series=' + series.seriesUID + '&object='
					+ series.instance[i].sopIUID + '&rows=512'
					+ '&contentType=image/png';

			}
			imagesid.push(imageURL);
		}
	}
}

// 取序列列表用于显示（的内容）
// Generate the series list on the left panel
function generateSeriesList(hosturl, serverURL, studyUID, seriesArray, series) {
	var sNum = series.length;

	// update by wujunbo
	// ------------------------------------屏幕序列横竖转换----------------------------------------------start

	var hh = '<div ><table class="table"><tbody>';
	var tr1 = '<div id="seriesList" style="height: 80px; overflow-y: scroll;">';
//	var tr1 = '<tr>';
	// update by wujunbo
	// ------------------------------------屏幕序列横竖转换----------------------------------------------end
	var nav1 = '';
	nav1 += '<table class="table" style="background-color: #000;"><thead><tr>'
		+ '<th style="width:72px;border: none;color:#E7E7E7;">影像</th>'
		+ '<th style="width:48px;border: none;color:#E7E7E7;">数量</th>'
		+ '</tr></thead><tbody>';

	for (var i = 0; i < sNum; i++) {
		var index = i + 1;
		var insNum = seriesArray[i].instance.length;
		var middle = Math.floor(insNum / 2);
		var src = hosturl + '/imagecloud/read?' + 'serverURL=' + serverURL
			+ '/wado&study=' + String(studyUID) + '&series='
			+ seriesArray[i].seriesUID + '&object='
			+ seriesArray[i].instance[middle].sopIUID + '&rows=64';

		nav1 += '<tr>';
		nav1 += '<td colspan="2" style="color:white;text-align:center;border-color:white;">'+series[i].seriesDescription +'</td>';
		nav1 += '</tr>';
		nav1 += '<tr onclick="showSeriesByIndex(' + i + ',' + insNum + ')">';

		nav1 += '<td style="width:72px;border:none;padding:2px">' + '<a><img class="img-rounded"'
			+ 'onerror="imageNotfound();"' + ' src="' + src + '"'
			+ ' id="series' + i + '"' + ' onclick="showSeriesByIndex(' + i
			+ ',' + insNum + ')"' + 'height="50"' + ' alt="' + '序列' + i
			+ '"' + '/></a></td>';

		nav1 += '<td style="width:48px;color:#E7E7E7;vertical-align:middle;border:none;">' + insNum + '</td>';
		nav1 += '</tr>';

		// update by wujunbo
		// ------------------------------------屏幕序列横竖转换----------------------------------------------start
		tr1 += '<div style="width:72px;float: left">'
			+ '<a><img class="img-rounded"'
			+ 'onerror="imageNotfound();"'
			+ ' src="'
			+ src
			+ '"'
			+ ' id="series'
			+ i
			+ '"'
			+ ' onclick="showSeriesByIndex('
			+ i
			+ ','
			+ insNum
			+ ')"'
			+ 'height="50"'
			+ ' alt="'
			+ '序列'
			+ i
			+ '"'
			+ '/></a><div style="text-align: center;width: 47px;color:#E7E7E7;">'
			+ insNum + '</div></div>';
		// update by wujunbo
		// ------------------------------------屏幕序列横竖转换----------------------------------------------end

	}
	nav1 += '</tbody></table>';

	// update by wujunbo
	// ------------------------------------屏幕序列横竖转换----------------------------------------------start
	tr1 += '</div>';
	hh = tr1 + '</tbody></table></div>';
	// update by wujunbo
	// ------------------------------------屏幕序列横竖转换----------------------------------------------end
	$("#series").html(nav1);
	$("#series_transverse").html(hh);
	$("#series_transverse").width($("body").width() -2);
	// 修改序列列表的样式（修改tab1中显示列表的样式）
	changeTable();
}

function showSeriesByIndex(index, insNum) {
	cornerstone.imageCache.purgeCache();
	changgeSeriesByIndex = index;

	if (index === clickedSeries) {
		return;
	}

	clickedSeries = index;
	if(1 != iWindowVNum*iWindowHNum){
		return;
	}

	wheelInstanceNum[0] = 0;
	sort = index;

	cancelBindKey();
	loadButtonHint();

	groupIndex[0] = groupIndex[clickedSeries];

	$("#imageContainer").html('');
	var image = $("#slice-range").parent();
	image.html('');
	image.html('<input type="range" id="slice-range">');
	showSeries(iWindowVNum, iWindowHNum);
}

// display the layout
function changeLayout() {
//	recoverButtonColor();
	$('#grid').css('background-color','gray');

	cancelBindKey();
	loadButtonHint();
	jQuery('#contentDiv').html('');
	jQuery('#contentDiv').load('/app/main/Viewer/layout.html');
	jQuery('#contentDiv').show();

	jQuery("#contentDiv").mouseleave(function() {
		jQuery(this).hide();
	});
}

// 显示序列
function showSeries(colIndex, rowIndex) {
	$('#toolbar-function-simple').css('display','none');
	$('#toolbar-function').css('display','block');
	$('#mrtopleft').css('display','block');
	clickedSeries = -1;
	for(var i = 0; i < iSeriesNum; i++){
		if(loadedIndex[i] != -1){
			loadedIndex[i] = -1;
		}
	}

	autoPlayButtonPressed = true;

	$('#imageContainer').removeClass('adjust');
	$('#imageContainer').removeClass('move');
	$('#imageContainer').removeClass('zoom');
	//getDicomButtonPressed = false;

	initialWW = [];
	initialWL = [];
	globalWW = [];
	globalWL = [];
	imageScale = [];
	multiSeries = [];

	if(seriesArray.length < colIndex){
		colIndex = seriesArray.length;
	}
	
	if (colIndex * rowIndex > seriesArray.length) {
		rowIndex = Math.ceil(seriesArray.length / colIndex);
	}

	iWindowVNum = colIndex;
	iWindowHNum = rowIndex;
	viewportNum = iWindowHNum * iWindowVNum - 1;

	var divContent = '';

	var cnt = parseInt('0');

	for ( var x = 0; x < iWindowHNum; x++) {
		for ( var y = 0; y < iWindowVNum; y++) {
			// For each series, load it
			if (cnt < totalSeries) {
				var imageDivId = "image" + x.toString() + y.toString();
				// 解除上次绑定
				var element = $( '#' + imageDivId).get(0);
				$(element).off( "CornerstoneImageRendered");
				cnt++;
			}
		}
	}

	cnt = 0;

	if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
		cnt = parseInt(sort);
	}
	// TODO
	divContent += '<table id="tableViews" style="width:100%;border:1px solid #D5D5D5;background-color: #000;">';

	for (var x = 0; x < rowIndex; x++) {
		divContent += '<tr height="' + 100 / (rowIndex) + '%">';
		for (var y = 0; y < colIndex; y++) {

			// For each series, load it
			if (cnt < totalSeries) {
				var imageDivId = "image" + x.toString() + y.toString();
				divContent += '<td style="padding:0;margin:0;border:1px solid #454444;" width="'
					+ 100 / colIndex + '%" >';
				divContent += '<div style="width:'
					+ 100
					+ '%;'
					+ 'height:'
					+ 100
					+ '%'
					+ ';position:relative;display:inline-block;color:white;"'
					+ 'oncontextmenu="return false" class="cornerstone-enabled-image" unselectable="on" onselectstart="return false;"'
					+ 'onmousedown="return false;">';
				divContent += '<div id="' + imageDivId
					+ '" onclick="showCurrentSeries('
					+ imageDivId.toString() + ',' + cnt + ')"></div>';
				divContent += '</div>' + '</td>';

				cnt++;

			}
		}
		divContent += '</tr>';
	}
	divContent += '</table>';
	document.getElementById("imageContainer").innerHTML = divContent;

	var cnt = parseInt('0');
	if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
		cnt = parseInt(sort);
	}
	for (var x = 0; x < rowIndex; x++) {
		for (var y = 0; y < colIndex; y++) {
			// For each series, load it
			if (cnt < totalSeries) {
				var imageDivId = "image" + x.toString() + y.toString();
				// 设置图片显示位置区域
				showEachSeries(imageDivId, cnt);
				cnt++;
			}
		}
	}

}

// 设置图片显示位置区域
function showEachSeries(imageDivId, cnt) {
	wheelInstanceNum[cnt] = 0;
	var mydiv = $('#' + imageDivId);

	// Bottom Right
	var divBottomRight = $('<div></div>');
	divBottomRight.attr('id', 'mrbottomright' + cnt);
	divBottomRight.attr('style','position: absolute; bottom: 6px; right:10px; text-align:right; color: white;');
	divBottomRight.appendTo(mydiv);

	var	displayText = imageInfo.patientname + (imageInfo.patientname!=""?'<br/>':"")
		+ imageInfo.patientid + (imageInfo.patientid!=""?'<br/>':"");
	if (imageInfo.sex == 0) {
		displayText += 'M' + '<br/>';
	} else {
		displayText += 'F' + '<br/>';
	}
	displayText += imageInfo.institutionname + (imageInfo.institutionname!=""?'<br/>':"")
		+ imageInfo.studydescription + (imageInfo.studydescription!=""?'<br/>':"")
		+ series[cnt].seriesDescription + (series[cnt].seriesDescription!=""?'<br/>':"")
		+ (imageInfo.birthday!=""?'出生日期：':"") + imageInfo.birthday + (imageInfo.birthday!=""?'<br/>':"")
		+ (imageInfo.studydate!=""?'拍摄日期：':"") + imageInfo.studydate;
	$('#mrbottomright' + cnt).html(displayText);

	// Top Right
	var divTopRight = $('<div></div>');
	divTopRight.attr('id', 'mrtopright' + cnt);
	divTopRight.attr('style','position: absolute; top: 6px; right: 6px;  color: white; border');
	divTopRight.appendTo(mydiv);
	$('#mrtopright' + cnt).html('');

	// Bottom Left
	var divBottomLeft = $('<div></div>');
	divBottomLeft.attr('id', 'mrbottomleft' + cnt);
	divBottomLeft.attr('style','position: absolute; bottom: 6px; left: 6px;  color: white;');
	divBottomLeft.appendTo(mydiv);

	// Next four divs are used to display image orientation
	// Left
	var divLeft = $('<div></div>');
	divLeft.attr('id','mrdivLeft' + cnt);
	divLeft.attr('style','position: absolute; top: 0px; left: 20px; color: yellow;');
	divLeft.appendTo(mydiv);

	// Right
	var divRight = $('<div></div>');
	divRight.attr('id','mrdivRight' + cnt);
	divRight.attr('style','position: absolute; top: 0px; right: 20px; color: yellow;');
	divRight.appendTo(mydiv);

	// Top
	var divTop = $('<div></div>');
	divTop.attr('id','mrdivTop' + cnt);
	divTop.attr('style','position: absolute; top: 10px; left: 0px; color: yellow;');
	divTop.appendTo(mydiv);

	// Bottom
	var divBottom = $('<div></div>');
	divBottom.attr('id','mrdivBottom' + cnt);
	divBottom.attr('style','position: absolute; bottom: 20px; left: 0px; color: yellow;');
	divBottom.appendTo(mydiv);

	// For input and view
	function onViewportUpdated(e, data) {

		var div = e.currentTarget;
		var enabledElement = cornerstone.getEnabledElement(div);
		var viewport = enabledElement.viewport;
		var displayText;
		var instanceNum; // instance number displayed before the symbol "/", added by TanQilu
		var imageTotalNum; // total image number displayed after the symbol "/", added by TanQilu

		var curIndex = loadedIndex[cnt]==-1 ? cnt  : loadedIndex[cnt];

		// traverse the current or all series for the current instance ----------------------------------------- started by TanQilu
		for(var i = 0; i < seriesArray[curIndex].instance.length; i++){
			var startIndex = enabledElement.image.imageId.indexOf('object')+7;
			var endIndex = enabledElement.image.imageId.indexOf('&rows');
			if(enabledElement.image.imageId.substring(startIndex,endIndex) == seriesArray[curIndex].instance[i].sopIUID){
				instanceNum = seriesArray[curIndex].instance[i].instanceNumber;
				imageTotalNum = seriesArray[curIndex].instance.length;
				break;
			}
		}
		if(instanceNum == undefined){
			var hIndex = parseInt(cnt/iWindowVNum);
			var vIndex = cnt - parseInt(cnt/iWindowVNum)*iWindowVNum;
			var curDiv = $('#image'+hIndex.toString()+vIndex.toString()).get(0);
			var curElement;
			try{
				curElement = cornerstone.getEnabledElement(curDiv);
			}catch(another){
				curElement = cornerstone.getEnabledElement(div);
			}

			for(var i = 0; i < seriesArray[curIndex].instance.length; i++){
				var startIndex = curElement.image.imageId.indexOf('object')+7;
				var endIndex = curElement.image.imageId.indexOf('&rows');
				if(curElement.image.imageId.substring(startIndex,endIndex) == seriesArray[curIndex].instance[i].sopIUID){
					instanceNum = seriesArray[curIndex].instance[i].instanceNumber;
					imageTotalNum = seriesArray[curIndex].instance.length;
					break;
				}
			}
		}
		// --------------------------------------------------------------------------------------------------------- ended by TanQilu
		curImageNum = instanceNum; // export current variable to global variable
		if(initialWW[curIndex] == undefined || initialWL[curIndex] == undefined){
			initialWW[curIndex] = viewport.voi.windowWidth;
			initialWL[curIndex] = viewport.voi.windowCenter;
		}

		displayText = 'Img：' + (instanceNum+1) + '/'
			+ (imageTotalNum) + '<br/>' + 'WW：'
			+ Math.ceil(viewport.voi.windowWidth) + '&nbsp&nbsp'
			+ 'WL：' + Math.ceil(viewport.voi.windowCenter) + '<br/>'
			+ 'Zoom：' + viewport.scale.toFixed(2);
		$('#mrbottomleft' + cnt).html(displayText);

		// to mark the viewport which is selected
		var curElementId= div.id;
		$('#' + curElementId).css('border','1px solid #454444');
		$('#' + curElementId).css('border-color','#000');
		selectedViewportMarked(elementChoosed);

		if(isDesktop){
			plottingScale(div);

			// display the image orientation
			divLeft.get(0).style.top = ($('#'+div.id).height()/2).toString()+'px';
			divRight.get(0).style.top = ($('#'+div.id).height()/2).toString()+'px';
			divTop.get(0).style.left = ($('#'+div.id).width()/2).toString()+'px';
			divBottom.get(0).style.left = ($('#'+div.id).width()/2).toString()+'px';

			// get the series number and instance number
			var imgIndex = getImgIndex(div);

			// get the series number and instance number
			var instanceNum = imgIndex.instance;
			var seriesNum = imgIndex.series;

			if(tagArray[seriesNum][instanceNum].imageOrientation == undefined){
				return;
			}

			var Xx = parseFloat(tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[0]);
			var Xy = parseFloat(tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[1]);
			var Xz = parseFloat(tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[2]);
			var Yx = parseFloat(tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[3]);
			var Yy = parseFloat(tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[4]);
			var Yz = parseFloat(tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[5]);

			var leftDisp = '';
			var rightDisp = '';
			var topDisp = '';
			var bottomDisp = '';
			// Xx
			if(Xx > 0.1){
				leftDisp += 'R';
				rightDisp += 'L';
			} else if (Xx < -0.1){
				leftDisp += 'L';
				rightDisp += 'R';
			}
			// Xy
			if(Xy > 0.1){
				leftDisp += 'A';
				rightDisp += 'P';
			} else if (Xy < -0.1){
				leftDisp += 'P';
				rightDisp += 'A';
			}
			// Xz
			if(Xz > 0.1){
				leftDisp += 'I';
				rightDisp += 'S';
			} else if (Xz < -0.1){
				leftDisp += 'S';
				rightDisp += 'I';
			}
			//Yx
			if(Yx > 0.1){
				topDisp += 'R';
				bottomDisp += 'L';
			} else if (Yx < -0.1){
				topDisp += 'L';
				bottomDisp += 'R';
			}
			//Yy
			if(Yy > 0.1){
				topDisp += 'A';
				bottomDisp += 'P';
			} else if (Yy < -0.1){
				topDisp += 'P';
				bottomDisp += 'A';
			}
			//Yz
			if(Yz > 0.1){
				topDisp += 'I';
				bottomDisp += 'S';
			} else if (Yz < -0.1){
				topDisp += 'S';
				bottomDisp += 'I';
			}

			divLeft.html(leftDisp);
			divRight.html(rightDisp);
			divTop.html(topDisp);
			divBottom.html(bottomDisp);
		}
	};

	var element = $('#' + imageDivId).get(0);

	// image enable the dicomImage element and the mouse inputs
	cornerstone.enable(element);

	var imageIDs = [];
	// load images 找到序列中的所有影像
	loadImages(hosturl, serverURL, studyUID, seriesArray[cnt], imageIDs,
		imageType);
	var stack = {
		currentImageIdIndex : 0,
		imageIds : imageIDs
	};

	// Bind hotkeys
	jQuery(document).bind('keydown.1', function(evt) {
		$('#modalProgressGlobal').modal('show');
		contrastButtonPressed = true ;
		var newImageId = getDicom(element);

		cornerstone.loadAndCacheImage(newImageId).then( function(image){
			cornerstone.displayImage(element,image);
			var viewport = cornerstone.getEnabledElement(element).viewport;

			var seriesNum = getImgIndex(element).series;
			initialWL[seriesNum] = image.windowCenter;
			initialWW[seriesNum] = image.windowWidth;

			viewport.voi.windowCenter = 35;
			viewport.voi.windowWidth = 80;

			// element 的行列索引
			var eleRowIndex = element.id.substring(
				element.id.indexOf('image')+5,
				element.id.indexOf('image')+6);
			var eleColumnIndex = element.id.substring(
				element.id.indexOf('image')+6);
			eleRowIndex = parseInt(eleRowIndex);
			eleColumnIndex = parseInt(eleColumnIndex);

			var elementIdx = 0;
			if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
				elementIdx = parseInt(sort);
			} else {
				elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
			}

			globalWL[elementIdx] = 35;
			globalWW[elementIdx] = 80;

			cornerstone.setViewport(element,viewport);
			triggerResize();
			$('#modalProgressGlobal').modal('hide');
		});

		cornerstoneTools.wwwc.activate(element,1);
	});

	jQuery(document).bind('keydown.2', function(evt) {
		$('#modalProgressGlobal').modal('show');
		contrastButtonPressed = true ;
		var newImageId = getDicom(element);

		cornerstone.loadAndCacheImage(newImageId).then( function(image){
			cornerstone.displayImage(element,image);
			var viewport = cornerstone.getEnabledElement(element).viewport;

			var seriesNum = getImgIndex(element).series;
			initialWL[seriesNum] = image.windowCenter;
			initialWW[seriesNum] = image.windowWidth;

			viewport.voi.windowCenter = -500;
			viewport.voi.windowWidth = 1500;

			// element 的行列索引
			var eleRowIndex = element.id.substring(
				element.id.indexOf('image')+5,
				element.id.indexOf('image')+6);
			var eleColumnIndex = element.id.substring(
				element.id.indexOf('image')+6);
			eleRowIndex = parseInt(eleRowIndex);
			eleColumnIndex = parseInt(eleColumnIndex);

			var elementIdx = 0;
			if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
				elementIdx = parseInt(sort);
			} else {
				elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
			}

			globalWL[elementIdx] = -500;
			globalWW[elementIdx] = 1500;

			cornerstone.setViewport(element,viewport);
			triggerResize();
			$('#modalProgressGlobal').modal('hide');
		});

		cornerstoneTools.wwwc.activate(element,1);
	});

	jQuery(document).bind('keydown.3', function(evt) {
		$('#modalProgressGlobal').modal('show');
		contrastButtonPressed = true ;
		var newImageId = getDicom(element);

		cornerstone.loadAndCacheImage(newImageId).then( function(image){
			cornerstone.displayImage(element,image);
			var viewport = cornerstone.getEnabledElement(element).viewport;

			var seriesNum = getImgIndex(element).series;
			initialWL[seriesNum] = image.windowCenter;
			initialWW[seriesNum] = image.windowWidth;

			viewport.voi.windowCenter = 50;
			viewport.voi.windowWidth = 500;

			// element 的行列索引
			var eleRowIndex = element.id.substring(
				element.id.indexOf('image')+5,
				element.id.indexOf('image')+6);
			var eleColumnIndex = element.id.substring(
				element.id.indexOf('image')+6);
			eleRowIndex = parseInt(eleRowIndex);
			eleColumnIndex = parseInt(eleColumnIndex);

			var elementIdx = 0;
			if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
				elementIdx = parseInt(sort);
			} else {
				elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
			}

			globalWL[elementIdx] = 50;
			globalWW[elementIdx] = 500;

			cornerstone.setViewport(element,viewport);
			triggerResize();
			$('#modalProgressGlobal').modal('hide');
		});

		cornerstoneTools.wwwc.activate(element,1);
	});

	jQuery(document).bind('keydown.4', function(evt) {
		$('#modalProgressGlobal').modal('show');
		contrastButtonPressed = true ;
		var newImageId = getDicom(element);

		cornerstone.loadAndCacheImage(newImageId).then( function(image){
			cornerstone.displayImage(element,image);
			var viewport = cornerstone.getEnabledElement(element).viewport;

			var seriesNum = getImgIndex(element).series;
			initialWL[seriesNum] = image.windowCenter;
			initialWW[seriesNum] = image.windowWidth;

			viewport.voi.windowCenter = 50;
			viewport.voi.windowWidth = 350;

			// element 的行列索引
			var eleRowIndex = element.id.substring(
				element.id.indexOf('image')+5,
				element.id.indexOf('image')+6);
			var eleColumnIndex = element.id.substring(
				element.id.indexOf('image')+6);
			eleRowIndex = parseInt(eleRowIndex);
			eleColumnIndex = parseInt(eleColumnIndex);

			var elementIdx = 0;
			if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
				elementIdx = parseInt(sort);
			} else {
				elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
			}

			globalWL[elementIdx] = 50;
			globalWW[elementIdx] = 350;

			cornerstone.setViewport(element,viewport);
			triggerResize();
			$('#modalProgressGlobal').modal('hide');
		});

		cornerstoneTools.wwwc.activate(element,1);
	});

	jQuery(document).bind('keydown.5', function(evt) {
		$('#modalProgressGlobal').modal('show');
		contrastButtonPressed = true ;
		var newImageId = getDicom(element);

		cornerstone.loadAndCacheImage(newImageId).then( function(image){
			cornerstone.displayImage(element,image);
			var viewport = cornerstone.getEnabledElement(element).viewport;

			var seriesNum = getImgIndex(element).series;
			initialWL[seriesNum] = image.windowCenter;
			initialWW[seriesNum] = image.windowWidth;;

			viewport.voi.windowCenter = 300;
			viewport.voi.windowWidth = 1500;

			// element 的行列索引
			var eleRowIndex = element.id.substring(
				element.id.indexOf('image')+5,
				element.id.indexOf('image')+6);
			var eleColumnIndex = element.id.substring(
				element.id.indexOf('image')+6);
			eleRowIndex = parseInt(eleRowIndex);
			eleColumnIndex = parseInt(eleColumnIndex);

			var elementIdx = 0;
			if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
				elementIdx = parseInt(sort);
			} else {
				elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
			}

			globalWL[elementIdx] = 300;
			globalWW[elementIdx] = 1500;

			cornerstone.setViewport(element,viewport);
			triggerResize();
			$('#modalProgressGlobal').modal('hide');
		});

		cornerstoneTools.wwwc.activate(element,1);
	});

	// this function is used in keyboard hotkeys, aiming to browse to the location of
	// an special instance --------------------------------------- Updated by TanQilu
	function hotkeyBrowse(step,key){
		$('#imageContainer').removeClass('adjust');
		$('#enableWindowLevelTool').css('background-color','#000');
		contrastButtonPressed = false;

		recoverButtonColor();
		cornerstoneTools.wwwc.deactivate(element,1);

		// get the number of the selected element
		elementChoosed = elementChoosed || $('#image00').get(0);
		var eleRowIndex = elementChoosed.id.substring(
			elementChoosed.id.indexOf('image')+5,
			elementChoosed.id.indexOf('image')+6);
		var eleColumnIndex = elementChoosed.id.substring(
			elementChoosed.id.indexOf('image')+6);
		eleRowIndex = parseInt(eleRowIndex);
		eleColumnIndex = parseInt(eleColumnIndex);
		var eleIndex = eleRowIndex*iWindowVNum+eleColumnIndex;

		// get the scale of every window which will display the next image
		var enabledElement = cornerstone.getEnabledElement(elementChoosed);

		// delete the last image
		var canvas = enabledElement.canvas;
		var context = canvas.getContext('2d');
		context.clearRect(0,0,canvas.width,canvas.height);
		context.transform(1,0,0,1,0,0);

		context.textAlign = 'left';
		context.textBaseline = 'top';
		context.strokeStyle = '#DF5326';
		context.font = 'bold 24px arial';
		context.fillStyle = 'orange';
		context.fillText("载入中...", canvas.width/2 - 50, canvas.height/2+12);

		switch(key){
			case('left'):
			case('down'):
			case('pagedown'):
				wheelInstanceNum[eleIndex] = wheelInstanceNum[eleIndex] - step;
				break;
			case('right'):
			case('up'):
			case('pageup'):
				wheelInstanceNum[eleIndex] = wheelInstanceNum[eleIndex] + step;
				break;
			default:
		}

		// record the scale of current image
		var imgIndex = getImgIndex(elementChoosed);
		var row = parseInt(tagArray[imgIndex.series][imgIndex.instance].rows);
		var rowScale = 1;
		if(cornerstone.getImage(elementChoosed).data != undefined){ // DICOM
			rowScale = row/512;
		}
		var viewport = cornerstone.getEnabledElement(elementChoosed).viewport;
		imageScale[eleIndex] = (viewport.scale*rowScale).toFixed(2);

		var seriesIndex = getImgIndex(elementChoosed).series;
		var seriesNums = seriesArray[seriesIndex].instance.length;

		// show the new image with current WWWL
		if(wheelInstanceNum[eleIndex] >= seriesNums){
			wheelInstanceNum[eleIndex] = seriesNums-1;
		} else if(wheelInstanceNum[eleIndex] < 0){
			wheelInstanceNum[eleIndex] = 0;
		}
		readjustInstanceWWWL(wheelInstanceNum[eleIndex],elementChoosed);
	}

//	jQuery(document).unbind('keydown.home');
//	jQuery(document).bind('keydown.home', function(evt) {
//		selectNewImage(0);
//	});
//
//	jQuery(document).unbind('keydown.end');
//	jQuery(document).bind('keydown.end', function(evt) {
//		var sortedInstanceLength = [];
//		for(var i = 0; i < iSeriesNum; i++){
//			sortedInstanceLength[i] = seriesArray[i].instance.length;
//		}
//		sortedInstanceLength.sort(compare);
//		for(var i = 0; i < iSeriesNum; i++){
//			selectNewImage(sortedInstanceLength[i]-1);
//		}
//		function compare(value1,value2) {
//			return value1 - value2;
//		}
//	});

	jQuery(document).unbind('keydown.pageup');
	jQuery(document).bind('keydown.pageup', function(evt) {
		hotkeyBrowse(10,'pageup');
	});

	jQuery(document).unbind('keydown.pagedown');
	jQuery(document).bind('keydown.pagedown', function(evt) {
		hotkeyBrowse(10,'pagedown');
	});

	jQuery(document).unbind('keydown.left');
	jQuery(document).bind('keydown.left', function(evt) {
		hotkeyBrowse(1,'left');
	});

	jQuery(document).unbind('keydown.up');
	jQuery(document).bind('keydown.up', function(evt) {
		hotkeyBrowse(1,'up');
	});

	jQuery(document).unbind('keydown.right');
	jQuery(document).bind('keydown.right', function(evt) {
		hotkeyBrowse(1,'right');
	});

	jQuery(document).unbind('keydown.down');
	jQuery(document).bind('keydown.down', function(evt) {
		hotkeyBrowse(1,'down');
	});

	jQuery(document).bind('keydown.R', function(evt) {
		cornerstone.fitToWindow(element);

		var viewport = cornerstone.getViewport(element);
		if (viewport.invert === true) {
			viewport.invert = false;
		}
		cornerstone.setViewport(element, viewport);
	});

	$(element).on("CornerstoneImageRendered", onViewportUpdated);

	function onNewImage(e, data) {
		var newImageIdIndex = stack.currentImageIdIndex;

		// Update the slider value
		var slider = document.getElementById('slice-range');
		slider.value = newImageIdIndex;

		var div = e.currentTarget;
		var enabledElement = cornerstone.getEnabledElement(div);

	};

	$(element).on("CornerstoneNewImage", onNewImage);

	for (var i=0;i<imageIDs.length;i++)
	{
		cornerstone
			.loadAndCacheImage(imageIDs[i]);
	}

	// Ryan Add
	var curImageIDStr = '';
	if (series[cnt].modality == "DX" ||
		series[cnt].modality == "DR" ||
		series[cnt].modality == "CR" ){
		var imageIDs = [];
		var idNum = curImageIDStr.length;
		curImageIDStr = curImageIDStr.substr(0,idNum-3)+ ''
		imageIDs[i] == curImageIDStr;
		loadImages(hosturl, serverURL, studyUID, seriesArray[cnt], imageIDs,
			'dicom');
	}

	cornerstone
		.loadAndCacheImage(imageIDs[0])
		.done(
		function(image) {

		// 开启鼠标操作的功能
		if (isDesktop === true) {
			// 鼠标按下去滑动时间
			cornerstoneTools.mouseInput.enable(element);
			// 开启鼠标滑轮的操作
			//	cornerstoneTools.mouseWheelInput.enable(element);

			// 自定义鼠标滑轮
			$(element).on('mousewheel DOMMouseScroll',mouseWheel);

		}

		// 开启手机的手势操作功能
		if (isMobile === true) {
			cornerstoneTools.touchInput.enable(element);
		}

		// display this image
		cornerstone.displayImage(element, image);

		// set the stack as tool state
		cornerstoneTools.addStackStateManager(element,[ 'stack' ]);
		cornerstoneTools.addToolState(element, 'stack', stack);

		if (isDesktop === true) {
			//		cornerstoneTools.wwwc.activate(element, 1); // ww/wc is the default tool for left mouse button
			cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
			cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button
			cornerstoneTools.probe.enable(element);
			cornerstoneTools.length.enable(element);
			cornerstoneTools.ellipticalRoi.enable(element);
			cornerstoneTools.rectangleRoi.enable(element);
			cornerstoneTools.angle.enable(element);
			cornerstoneTools.highlight.enable(element);

			// 激活鼠标滑轮的功能
			//		cornerstoneTools.stackScrollWheel.activate(element);
		}

		if (isMobile === true) {
			// stack scroll
			cornerstoneTools.stackScrollTouchDrag.activate(element);
		}

		var curGroupIndex = groupIndex[cnt];
		synchronizers[curGroupIndex].add(element);
		multiSeries.push(parseInt(1));

		function disableAllTools() {
			if (isDesktop === true) {
				cornerstoneTools.wwwc.disable(element);
				$(element).off( 'CornerstoneToolsMouseDrag',mouseDragWWWL);
				cornerstoneTools.pan.activate(element, 2); // 2 is middle mouse button
				cornerstoneTools.zoom.activate(element, 4); // 4 is right mouse button
				cornerstoneTools.probe.deactivate(element, 1);
				cornerstoneTools.length.deactivate(element, 1);
				cornerstoneTools.ellipticalRoi.deactivate(element, 1);
				cornerstoneTools.rectangleRoi.deactivate(element, 1);
				cornerstoneTools.simpleAngle.deactivate(element, 1);
				cornerstoneTools.highlight.deactivate(element, 1);
				cornerstoneTools.freehand.deactivate(element, 1);
				cornerstoneTools.wwwcRegion.disable(element);

				$('#imageContainer').removeClass('adjust');
				$('#imageContainer').removeClass('move');
				$('#imageContainer').removeClass('zoom');
			}
			if (isMobile === true) {
				cornerstoneTools.panTouchDrag.deactivate(element);
				cornerstoneTools.rotateTouchDrag.deactivate(element);
				cornerstoneTools.rotateTouch.disable(element);
				cornerstoneTools.ellipticalRoiTouch.deactivate(element);
				cornerstoneTools.simpleAngleTouch.deactivate(element);
				cornerstoneTools.rectangleRoiTouch.deactivate(element);
				cornerstoneTools.lengthTouch.deactivate(element);
				cornerstoneTools.probeTouch.deactivate(element);
				cornerstoneTools.zoomTouchDrag.deactivate(element);
				cornerstoneTools.wwwcTouchDrag.deactivate(element);
				cornerstoneTools.stackScrollTouchDrag.deactivate(element);
				$('#image00').off( 'CornerstoneToolsTouchDrag' );
			}
		}


				function clearIconsColor(iconID) {
					$("#enableWindowLevelTool span").css("color","#505050");
					$("#zoom span").css("color","#505050");
					$("#enableLength span").css("color","#505050");
					$("#probe span").css("color","#505050");
					$("#circleroi span").css("color","#505050");
					$("#ShowAnnotation span").css("color","#505050");
					$("#UnShowAnnotation span").css("color","#505050");
					$("#saveImg span").css("color","#505050");
					$("#rectangleroi span").css("color","#505050");
					$("#angle span").css("color","#505050");
					$("#wwwc span").css("color","#505050");
					$("#pan span").css("color","#505050");
					$("#"+iconID+" span").css("color","#38c500");
				}


				// the mouseWheel event defined by me -------------------------------Updated by TanQilu
				function mouseWheel(e){
					$('#imageContainer').removeClass('adjust');
					$('#enableWindowLevelTool').css('background-color','#000');
					contrastButtonPressed = false;

					disableAllTools();
					recoverButtonColor();
					cornerstoneTools.wwwc.deactivate(element,1);

					for(var i = 0; i < iWindowHNum*iWindowVNum; i++){
						if(i >= seriesArray.length ){
							break;
						}
						// find the row and column indexes of this element
						var eleRowIdx = parseInt(i/iWindowVNum);
						var eleColumnIdx = parseInt(i-eleRowIdx*iWindowVNum);
						var curElement = $('#image' + eleRowIdx.toString() + eleColumnIdx.toString()).get(0);
						if(curElement == undefined){
							continue;
						}

						$(curElement).off( 'CornerstoneToolsMouseDrag');

						var seriesNum = getImgIndex(curElement).series;

						if(groupIndex[i] == groupIndex[cnt]){
							// if(synchrSwitch == false) {
							// 	if(i != cnt) continue;
							// }
							// get the scale of every window which will display the next image
							var enabledElement = cornerstone.getEnabledElement(curElement);

							// delete the last image
							var canvas = enabledElement.canvas;
							var context = canvas.getContext('2d');
							context.clearRect(0,0,canvas.width,canvas.height);
							context.transform(1,0,0,1,0,0);
							/*
							 context.font = 'italic bold 40px Arial';
							 context.textAlign = 'center';
							 context.textBaseline = 'middle';
							 var linearGrad = context.createLinearGradient(canvas.width/4,canvas.height/2,
							 3*canvas.width/4,canvas.height/2);
							 linearGrad.addColorStop(0.0,'red');
							 linearGrad.addColorStop(0.5,'yellow');
							 linearGrad.addColorStop(1.0,'green');
							 context.strokeStyle = linearGrad;
							 context.strokeText('loading...',canvas.width/2,canvas.height/2);
							 */


					context.textAlign = 'left';
					context.textBaseline = 'top';
					context.strokeStyle = '#DF5326';
					context.font = 'bold 24px arial';
					context.fillStyle = 'orange';
					context.fillText("载入中...", canvas.width/2 - 50, canvas.height/2+12);

					var imgIndex = getImgIndex(curElement);
					var row = parseInt(tagArray[imgIndex.series][imgIndex.instance].rows);
					var rowScale = 1;
					if(cornerstone.getImage(curElement).data != undefined){ // DICOM
						rowScale = row/512;
					}
					var viewport = cornerstone.getEnabledElement(curElement).viewport;
					imageScale[i] = (viewport.scale*rowScale).toFixed(2);
					imageScale[i]=(rowScale).toFixed(2);
//todo
					// display the next image of the current window and its synchronized windows
					if(e.originalEvent.deltaY > 0){
						if(wheelInstanceNum[i]+1 < seriesArray[seriesNum].instance.length){
							wheelInstanceNum[i]++;
						}
					} else if(e.originalEvent.deltaY < 0) {
						if(wheelInstanceNum[i]-1 > -1){
							wheelInstanceNum[i]--;
						}
					}
					//	 if(getDicomButtonPressed){
					//		selectNewImage(wheelInstanceNum[i]);
					//	 } else {
					readjustInstanceWWWL(wheelInstanceNum[i], curElement);
					//	 }

					var endIdx = curElement.children[2].innerHTML.indexOf('Img：')+4;
					var startIdx = curElement.children[2].innerHTML.indexOf('/');
					var displatText = curElement.children[2].innerHTML.substring(0,endIdx) +
						(wheelInstanceNum[i]+1).toString() +
						curElement.children[2].innerHTML.substring(startIdx);
					curElement.children[2].innerHTML = displatText;
					if(referenceLineButtonPressed){
						updateAllImageDisplayed();
						drawReferenceLine(element);
					}
				}
			}
		}

		// when the ww/wc is being adjusted, this mouseDrag event is
		// used to record the current ww/wc ------ Updated by TanQilu
		function mouseDragWWWL(e,eventData){
			cornerstone.imageCache.purgeCache();
			for(var eleRowIndex = 0; eleRowIndex < iWindowHNum; eleRowIndex++){
				for(var eleColumnIndex = 0; eleColumnIndex < iWindowVNum; eleColumnIndex++){
					var elementIdx  = 0;

					if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
						elementIdx = parseInt(sort);
					} else {
						elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
					}
					if(elementIdx < iSeriesNum){
						// get the window width from the viewport
						var startIndexOfWW = $('#mrbottomleft' +elementIdx.toString()).html().indexOf("WW" )+3;
						var endIndexOfWW = $('#mrbottomleft' +elementIdx.toString()).html().indexOf("&nbsp" );
						var newWW = $('#mrbottomleft' +elementIdx.toString()).html().substring(startIndexOfWW,endIndexOfWW);
						globalWW[elementIdx] = parseInt(newWW,10);
						if(globalWW[elementIdx]<=1){
							globalWW[elementIdx] = 1;
						}

						// get the window center from the viewport
						var startIndexOfWL = $('#mrbottomleft' +elementIdx.toString()).html().indexOf("WL" )+3;
						var endIndexOfWL = $('#mrbottomleft' +elementIdx.toString()).html().indexOf("<br>Zoom" );
						var newWL = $('#mrbottomleft' +elementIdx.toString()).html().substring(startIndexOfWL,endIndexOfWL);
						globalWL[elementIdx] = parseInt(newWL,10);
					}
				}
			}
		}

		// Tool button event handlers that set the new active
		$('#enableWindowLevelTool').click(function() {
			//			$('#modalProgressGlobal').modal('show');
			disableAllTools();
			recoverButtonColor();
			clearIconsColor("enableWindowLevelTool");
			$('#enableWindowLevelTool').css('background-color','gray');

			$('#imageContainer').addClass('adjust');
			lmViewer.data.contrastButtonPressed = true;
			var newImageId = getDicom(element);

			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;
				viewport.voi.windowCenter = image.windowCenter;
				viewport.voi.windowWidth = image.windowWidth;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);
				var elementIdx = eleRowIndex*lmViewer.data.iWindowVNum+eleColumnIndex;

				lmViewer.data.globalWL[elementIdx] = image.windowCenter;
				lmViewer.data.globalWW[elementIdx] = image.windowWidth;
				lmViewer.data.initialWL[elementIdx] = lmViewer.data.globalWL[elementIdx];
				lmViewer.data.initialWW[elementIdx] = lmViewer.data.globalWW[elementIdx];

				cornerstone.setViewport(element,viewport);
				triggerResize();
			});

			if (lmViewer.data.isDesktop === true) {
				// record the current window width and center, used on PC
				$(element).off( 'CornerstoneToolsMouseDrag');
				$(element).on( 'CornerstoneToolsMouseDrag',mouseDragWWWL);
				cornerstoneTools.wwwc.activate(element,1);
			}
			if(lmViewer.data.isMobile) {
				// record the current window width and center
				$( '#image00').on( 'CornerstoneToolsTouchDrag' ,function (e,eventData){
					cornerstoneTools.wwwcTouchDrag.activate(element);

					var elementIdx = parseInt(lmViewer.data.sort);
					// get the window width from the viewport
					var startIndexOfWW = $('#mrbottomleft' +lmViewer.data.sort.toString()).html().indexOf("WW" )+3;
					var endIndexOfWW = $('#mrbottomleft' +lmViewer.data.sort.toString()).html().indexOf("&nbsp" );
					var newWW = $('#mrbottomleft' +lmViewer.data.sort.toString()).html().substring(startIndexOfWW,endIndexOfWW);
					lmViewer.data.globalWW[elementIdx] = parseInt(newWW,10);

					// get the window center from the viewport
					var startIndexOfWL = $('#mrbottomleft' +lmViewer.data.sort.toString()).html().indexOf("WL" )+3;
					var endIndexOfWL = $('#mrbottomleft' +lmViewer.data.sort.toString()).html().indexOf("<br>Zoom" );
					var newWL = $('#mrbottomleft' +lmViewer.data.sort.toString()).html().substring(startIndexOfWL,endIndexOfWL);
					lmViewer.data.globalWL[elementIdx] = parseInt(newWL,10);
				});
			}

			$('#modalProgressGlobal').modal('hide');
		});

		$('#enableScrollStack').click(function() {
			humane.log( "滑动滚动浏览" );
			disableAllTools();
			recoverButtonColor();
			$('#enableScrollStack').css('background-color','gray');

			if (lmViewer.data.isDesktop === true) {
				cornerstoneTools.stackScrollWheel.activate(element);
			}
			if (lmViewer.data.isMobile === true) {
				// get the scale of every window which will display the next image
				var curElement = $('#image00').get(0);
				var enabledElement = cornerstone.getEnabledElement(curElement);
				var imgIndex = getImgIndex(curElement);
				var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
				var rowScale = 1;
				if(cornerstone.getImage(curElement).data != undefined){ // DICOM
					rowScale = row/512;
				}
				var viewport = cornerstone.getEnabledElement(curElement).viewport;
				lmViewer.data.imageScale[0] = (viewport.scale*rowScale).toFixed(2);

				$( '#image00').on( 'CornerstoneToolsTouchDrag' ,function (e,eventData){
					if(eventData.deltaPoints.image.y > 0){
						if(lmViewer.data.curImageNum+1 < lmViewer.data.seriesArray[sort].instance.length){
							lmViewer.data.curImageNum++;
						}
						//              if(contrastButtonPressed && navigator.userAgent.indexOf( 'iPhone') == -1){
						readjustInstanceWWWL(lmViewer.data.curImageNum,curElement);
						//             } else {
						//                   selectNewImage(curImageNum);
						//             }

					} else if(eventData.deltaPoints.image.y < 0) {
						if(lmViewer.data.curImageNum-1 > -1){
							lmViewer.data.curImageNum--;
						}
						//              if(contrastButtonPressed && navigator.userAgent.indexOf( 'iPhone') == -1){
						readjustInstanceWWWL(lmViewer.data.curImageNum,curElement);
						//             } else {
						//                   selectNewImage(curImageNum);
						//             }
					}
				});
				//          cornerstoneTools.stackScrollTouchDrag.activate(element);
			}
		});

		$('#pan').click(function() {
			disableAllTools();
			recoverButtonColor();
			$('#pan').css('background-color','gray');
			clearIconsColor("pan");
			$('#imageContainer').addClass('move');

			if (lmViewer.data.isDesktop === true) {
				cornerstoneTools.pan.activate(element, 3);
			}
			if (lmViewer.data.isMobile === true) {
				cornerstoneTools.panTouchDrag.activate(element);
			}
		});

		$('#zoom').click(function() {
			console.log("#zoom is running....");

			disableAllTools();
			recoverButtonColor();
			clearIconsColor("zoom");
			$('#zoom').css('background-color','gray');

			$('#imageContainer').addClass('zoom');
			if (lmViewer.data.isDesktop === true) {
				cornerstoneTools.zoom.activate(element,
					5);
				// 5 means left mouse button and right
				// mouse button
			}
			if (lmViewer.data.isMobile === true) {
				cornerstoneTools.zoomTouchDrag.activate(element);
			}
		});

		$('#RotateLeft').click(function() {
			disableAllTools();
			recoverButtonColor();
			$('#RotateLeft').css('background-color','gray');

			var enabledElement = cornerstone
				.getEnabledElement(element);
			enabledElement.viewport.rotation = enabledElement.viewport.rotation - 90;
			cornerstone.updateImage(element);
		});
		$('#RotateRight').click(function() {
			disableAllTools();
			recoverButtonColor();
			$('#RotateRight').css('background-color','gray');

			var enabledElement = cornerstone
				.getEnabledElement(element);
			enabledElement.viewport.rotation = enabledElement.viewport.rotation + 90;
			cornerstone.updateImage(element);
		});

		$('#hFlip').click(function(e) {
			recoverButtonColor();
			$('#hFlip').css('background-color','gray');

			var viewport = cornerstone.getViewport(element);
			viewport.hflip = !viewport.hflip;
			cornerstone.setViewport(element, viewport);
		});

		$('#vFlip').click(function(e) {
			recoverButtonColor();
			$('#vFlip').css('background-color','gray');

			var viewport = cornerstone.getViewport(element);
			viewport.vflip = !viewport.vflip;
			cornerstone.setViewport(element, viewport);
		});

		$('#reset').click(function() {
			disableAllTools();
			recoverButtonColor();
			$('#reset').css('background-color','gray');

			cornerstone.fitToWindow(element);
			var viewport = cornerstone.getViewport(element);
			if (viewport.invert === true) {
				viewport.invert = false;
			}
			cornerstone.setViewport(element, viewport);
		});


		$('#enableLength').click(function() {
			disableAllTools();
			recoverButtonColor();
			clearIconsColor("enableLength");
			$('#enableLength').css('background-color','gray');

			// get the scale of every window which will display the next image
			var enabledElement = cornerstone.getEnabledElement(element);
			var imgIndex = getImgIndex(element);
			var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
			var rowScale = 1;
			if(cornerstone.getImage(element).data == undefined){ // JPG
				rowScale = 512/row;
			}

			var newImageId = getDicom(element);
			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);
				var elementIdx = 0;
				if(lmViewer.data.iWindowVNum*lmViewer.data.iWindowHNum==1){
					elementIdx = lmViewer.data.sort;
				} else {
					elementIdx = eleRowIndex*lmViewer.data.iWindowVNum+eleColumnIndex;
				}

				lmViewer.data.initialWL[elementIdx] = image.windowCenter;
				lmViewer.data.initialWW[elementIdx] = image.windowWidth;
				if(lmViewer.data.globalWW[elementIdx]!=undefined && lmViewer.data.globalWL[elementIdx]!=undefined){
					viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
					viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
				} else {
					viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
					viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
				}

				lmViewer.data.imageScale[cnt] = parseFloat((viewport.scale*rowScale).toFixed(2));
				viewport.scale = lmViewer.data.imageScale[cnt];

				cornerstone.setViewport(element,viewport);
			});

			if (lmViewer.data.isDesktop === true) {
				cornerstoneTools.length.activate(element, 1);
			}
			if (lmViewer.data.isMobile === true) {
				cornerstoneTools.lengthTouch.activate(element);
			}

		});

		$('#probe').click(function() {
			//		$('#modalProgressGlobal').modal('show');
			disableAllTools();
			recoverButtonColor();
			clearIconsColor("probe");
			$('#probe').css('background-color','gray');

			// get the scale of every window which will display the next image
			var enabledElement = cornerstone.getEnabledElement(element);
			var imgIndex = getImgIndex(element);
			var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
			var rowScale = 1;
			if(cornerstone.getImage(element).data == undefined){ // JPG
				rowScale = 512/row;
			}

			var newImageId = getDicom(element);
			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);
				var elementIdx = 0;
				if(lmViewer.data.iWindowVNum*lmViewer.data.iWindowHNum==1){
					elementIdx = lmViewer.data.sort;
				} else {
					elementIdx = eleRowIndex*lmViewer.data.iWindowVNum+eleColumnIndex;
				}

				lmViewer.data.initialWL[elementIdx] = image.windowCenter;
				lmViewer.data.initialWW[elementIdx] = image.windowWidth;
				if(lmViewer.data.globalWW[elementIdx]!=undefined && lmViewer.data.globalWL[elementIdx]!=undefined){
					viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
					viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
				} else {
					viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
					viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
				}

				lmViewer.data.imageScale[cnt] = parseFloat((viewport.scale*rowScale).toFixed(2));
				viewport.scale = lmViewer.data.imageScale[cnt];

				cornerstone.setViewport(element,viewport);
			});
			if (lmViewer.data.isDesktop === true) {
				cornerstoneTools.probe.activate(element, 1);
			}
			if (lmViewer.data.isMobile === true) {
				cornerstoneTools.probeTouch.activate(element);
			}
		});

		$('#circleroi').click(function() {
			disableAllTools();
			recoverButtonColor();
			$('#circleroi').css('background-color','gray');
			clearIconsColor("circleroi");

			// get the scale of every window which will display the next image
			var enabledElement = cornerstone.getEnabledElement(element);
			var imgIndex = getImgIndex(element);
			var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
			var rowScale = 1;
			if(cornerstone.getImage(element).data == undefined){ // JPG
				rowScale = 512/row;
			}

			var newImageId = getDicom(element);
			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);
				var elementIdx = 0;
				if(lmViewer.data.iWindowVNum*lmViewer.data.iWindowHNum==1){
					elementIdx = lmViewer.data.sort;
				} else {
					elementIdx = eleRowIndex*lmViewer.data.iWindowVNum+eleColumnIndex;
				}

				lmViewer.data.initialWL[elementIdx] = image.windowCenter;
				lmViewer.data.initialWW[elementIdx] = image.windowWidth;
				if(lmViewer.data.globalWW[elementIdx]!=undefined && lmViewer.data.globalWL[elementIdx]!=undefined){
					viewport.voi.windowCenter = globalWL[elementIdx];
					viewport.voi.windowWidth = globalWW[elementIdx];
				} else {
					viewport.voi.windowCenter = initialWL[elementIdx];
					viewport.voi.windowWidth = initialWW[elementIdx];
				}

				imageScale[cnt] = parseFloat((viewport.scale*rowScale).toFixed(2));
				viewport.scale = imageScale[cnt];

				cornerstone.setViewport(element,viewport);
			});

			if (isDesktop === true) {
				cornerstoneTools.ellipticalRoi.activate(element, 1);
			}
			if (isMobile === true) {
				cornerstoneTools.ellipticalRoiTouch.activate(element);
			}

		});

		$('#rectangleroi').click(function() {
			disableAllTools();
			recoverButtonColor();
			$('#rectangleroi').css('background-color','gray');

			// get the scale of every window which will display the next image
			var enabledElement = cornerstone.getEnabledElement(element);
			var imgIndex = getImgIndex(element);
			var row = parseInt(tagArray[imgIndex.series][imgIndex.instance].rows);
			var rowScale = 1;
			if(cornerstone.getImage(element).data == undefined){ // JPG
				rowScale = 512/row;
			}

			var newImageId = getDicom(element);
			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);
				var elementIdx = 0;
				if(iWindowVNum*iWindowHNum==1){
					elementIdx = sort;
				} else {
					elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
				}

				initialWL[elementIdx] = image.windowCenter;
				initialWW[elementIdx] = image.windowWidth;
				if(globalWW[elementIdx]!=undefined && globalWL[elementIdx]!=undefined){
					viewport.voi.windowCenter = globalWL[elementIdx];
					viewport.voi.windowWidth = globalWW[elementIdx];
				} else {
					viewport.voi.windowCenter = initialWL[elementIdx];
					viewport.voi.windowWidth = initialWW[elementIdx];
				}

				imageScale[cnt] = parseFloat((viewport.scale*rowScale).toFixed(2));
				viewport.scale = imageScale[cnt];

				cornerstone.setViewport(element,viewport);
			});

			if (isDesktop === true) {
				cornerstoneTools.rectangleRoi.activate(element, 1);
			}
			if (isMobile === true) {
				cornerstoneTools.rectangleRoiTouch.activate(element);
			}
		});

		$('#angle').click(function() {
			disableAllTools();
			recoverButtonColor();
			$('#angle').css('background-color','gray');
			clearIconsColor("angle");

			if (isDesktop === true) {
				cornerstoneTools.simpleAngle.activate(element, 1);
			}
			if (isMobile === true) {
				cornerstoneTools.simpleAngleTouch.activate(element);
			}
		});

		$('#UnShowAnnotation').click(function(e) {
			disableAllTools();
			recoverButtonColor();
			$('#UnShowAnnotation').css('background-color','gray');

			cornerstoneTools.probe.disable(element);
			cornerstoneTools.rectangleRoi.disable(element);
			cornerstoneTools.ellipticalRoi.disable(element);
			cornerstoneTools.simpleAngle.disable(element);
			cornerstoneTools.lengthTouch.disable(element);
		});

		$('#ShowAnnotation').click(function(e) {
			disableAllTools();
			lmViewer.ui.recoverButtonColor();
			$('#ShowAnnotation').css('background-color','gray');

			cornerstoneTools.probe.enable(element);
			cornerstoneTools.rectangleRoi.enable(element);
			cornerstoneTools.ellipticalRoi.enable(element);
			cornerstoneTools.simpleAngle.enable(element);
			cornerstoneTools.lengthTouch.enable(element);
		});

		$( '#wwwc').click( function(e){
			disableAllTools();
			recoverButtonColor();
			$('#wwwc').css('background-color','gray');
			clearIconsColor("wwwc");

			if(isDesktop === true){
				cornerstoneTools.wwwcRegion.activate(element, 1);
			}
		});

		$('#invert').click(function(e) {
			recoverButtonColor();
			$('#invert').css('background-color','gray');

			var viewport = cornerstone.getViewport(element);
			if (viewport.invert === true) {
				viewport.invert = false;
			} else {
				viewport.invert = true;
			}
			cornerstone.setViewport(element, viewport);
		});

		$('#WindowLevelHead').click(function(e) {
			disableAllTools();
			recoverButtonColor();
			$('#WindowLevelHead').css('background-color','gray');
			//	$('#modalProgressGlobal').modal('show');
			$('#imageContainer').addClass('adjust');

			contrastButtonPressed = true ;
			var newImageId = getDicom(element);

			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				var seriesNum = getImgIndex(element).series;
				initialWL[seriesNum] = image.windowCenter;
				initialWW[seriesNum] = image.windowWidth;

				viewport.voi.windowCenter = 35;
				viewport.voi.windowWidth = 80;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);

				var elementIdx = 0;
				if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
					elementIdx = parseInt(sort);
				} else {
					elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
				}

				globalWL[elementIdx] = 35;
				globalWW[elementIdx] = 80;

				cornerstone.setViewport(element,viewport);
				triggerResize();
				$('#modalProgressGlobal').modal('hide');
			});

			cornerstoneTools.wwwc.activate(element,1);
			$(element).off( 'CornerstoneToolsMouseDrag');
			$(element).on( 'CornerstoneToolsMouseDrag',mouseDragWWWL);

			// record the current window width and center, used on PC

//							var viewport = cornerstone.getViewport(element);
//							viewport.voi.windowWidth = 80;
//							viewport.voi.windowCenter = 35;
//							cornerstone.setViewport(element, viewport);
		});

		$('#WindowLevelLung').click(function(e) {
			disableAllTools();
			recoverButtonColor();
			$('#WindowLevelLung').css('background-color','gray');
			//		$('#modalProgressGlobal').modal('show');
			$('#imageContainer').addClass('adjust');

			contrastButtonPressed = true ;
			var newImageId = getDicom(element);

			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				var seriesNum = getImgIndex(element).series;
				initialWL[seriesNum] = image.windowCenter;
				initialWW[seriesNum] = image.windowWidth;

				viewport.voi.windowCenter = -500;
				viewport.voi.windowWidth = 1500;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);

				var elementIdx = 0;
				if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
					elementIdx = parseInt(sort);
				} else {
					elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
				}

				globalWL[elementIdx] = -500;
				globalWW[elementIdx] = 1500;

				cornerstone.setViewport(element,viewport);
				triggerResize();
				$('#modalProgressGlobal').modal('hide');
			});

			cornerstoneTools.wwwc.activate(element,1);
			$(element).off( 'CornerstoneToolsMouseDrag');
			$(element).on( 'CornerstoneToolsMouseDrag',mouseDragWWWL);

//							var viewport = cornerstone.getViewport(element);
//							viewport.voi.windowWidth = 800;
//							viewport.voi.windowCenter = -700;
//							cornerstone.setViewport(element, viewport);
		});

		$('#WindowLevelChest').click(function(e) {
			disableAllTools();
			recoverButtonColor();
			$('#WindowLevelChest').css('background-color','gray');
			//			$('#modalProgressGlobal').modal('show');
			$('#imageContainer').addClass('adjust');

			contrastButtonPressed = true ;
			var newImageId = getDicom(element);

			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				var seriesNum = getImgIndex(element).series;
				initialWL[seriesNum] = image.windowCenter;
				initialWW[seriesNum] = image.windowWidth;

				viewport.voi.windowCenter = 50;
				viewport.voi.windowWidth = 500;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);

				var elementIdx = 0;
				if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
					elementIdx = parseInt(sort);
				} else {
					elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
				}

				globalWL[elementIdx] = 50;
				globalWW[elementIdx] = 500;

				cornerstone.setViewport(element,viewport);
				triggerResize();
				$('#modalProgressGlobal').modal('hide');
			});

			cornerstoneTools.wwwc.activate(element,1);
			$(element).off( 'CornerstoneToolsMouseDrag');
			$(element).on( 'CornerstoneToolsMouseDrag',mouseDragWWWL);

//							var viewport = cornerstone.getViewport(element);
//							viewport.voi.windowWidth = 500;
//							viewport.voi.windowCenter = 50;
//							cornerstone.setViewport(element, viewport);
		});

		$('#WindowLevelAbdomen').click(function(e) {
			disableAllTools();
			recoverButtonColor();
			$('#WindowLevelAbdomen').css('background-color','gray');
			//				$('#modalProgressGlobal').modal('show');
			$('#imageContainer').addClass('adjust');

			contrastButtonPressed = true ;
			var newImageId = getDicom(element);

			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				var seriesNum = getImgIndex(element).series;
				initialWL[seriesNum] = image.windowCenter;
				initialWW[seriesNum] = image.windowWidth;

				viewport.voi.windowCenter = 50;
				viewport.voi.windowWidth = 350;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);

				var elementIdx = 0;
				if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
					elementIdx = parseInt(sort);
				} else {
					elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
				}

				globalWL[elementIdx] = 50;
				globalWW[elementIdx] = 350;

				cornerstone.setViewport(element,viewport);
				triggerResize();
				$('#modalProgressGlobal').modal('hide');
			});

			cornerstoneTools.wwwc.activate(element,1);
			$(element).off( 'CornerstoneToolsMouseDrag');
			$(element).on( 'CornerstoneToolsMouseDrag',mouseDragWWWL);

//							var viewport = cornerstone.getViewport(element);
//							viewport.voi.windowWidth = 170;
//							viewport.voi.windowCenter = 35;
//							cornerstone.setViewport(element, viewport);
		});

		$('#WindowLevelBone').click(function(e) {
			disableAllTools();
			recoverButtonColor();
			$('#WindowLevelBone').css('background-color','gray');
			//			$('#modalProgressGlobal').modal('show');
			$('#imageContainer').addClass('adjust');

			contrastButtonPressed = true ;
			var newImageId = getDicom(element);

			cornerstone.loadAndCacheImage(newImageId).then( function(image){
				cornerstone.displayImage(element,image);
				var viewport = cornerstone.getEnabledElement(element).viewport;

				var seriesNum = getImgIndex(element).series;
				initialWL[seriesNum] = image.windowCenter;
				initialWW[seriesNum] = image.windowWidth;;

				viewport.voi.windowCenter = 300;
				viewport.voi.windowWidth = 1500;

				// element 的行列索引
				var eleRowIndex = element.id.substring(
					element.id.indexOf('image')+5,
					element.id.indexOf('image')+6);
				var eleColumnIndex = element.id.substring(
					element.id.indexOf('image')+6);
				eleRowIndex = parseInt(eleRowIndex);
				eleColumnIndex = parseInt(eleColumnIndex);

				var elementIdx = 0;
				if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
					elementIdx = parseInt(sort);
				} else {
					elementIdx = eleRowIndex*iWindowVNum+eleColumnIndex;
				}

				globalWL[elementIdx] = 300;
				globalWW[elementIdx] = 1500;

				cornerstone.setViewport(element,viewport);
				triggerResize();
				$('#modalProgressGlobal').modal('hide');
			});

			cornerstoneTools.wwwc.activate(element,1);
			$(element).off( 'CornerstoneToolsMouseDrag');
			$(element).on( 'CornerstoneToolsMouseDrag',mouseDragWWWL);

//							var viewport = cornerstone.getViewport(element);
//							viewport.voi.windowWidth = 1500;
//							viewport.voi.windowCenter = 300;
//							cornerstone.setViewport(element, viewport);
				});

				triggerResize();
				// $('#modalProgressGlobal').modal('hide');
				if(isDesktop){
					plottingScale(element);
				}
			});
}


// 序列对象排序
function sortSeries() {
	var tempSeriesArray = [];
//	var tempTagArray = [];
	var sNum = series.length;

	for (var i = 0; i < sNum; i++) {

		// find proper seriesID
		var poperIndex = '';
		for (var j = 0; j < sNum; j++) {
			if (series[i].seriesIUID == seriesArray[j].seriesUID) {
				tempSeriesArray.push(seriesArray[j]);
//				tempTagArray.push(tagArray[j]);
				break;
			}
		}
	}
	seriesArray = tempSeriesArray;
//	tagArray = tempTagArray;
}

function triggerResize() {
	// is loaded completely
	var itotal = 0;
	for (var i = 0; i < multiSeries.length; i++) {
		itotal = itotal + multiSeries[i];

	}
	if (itotal == iWindowVNum * iWindowHNum || itotal == totalSeries) {
		resizeCanvas();
		resizeSeriesDiv();
	}
}

function showCurrentSeries(element, index) {
	elementChoosed = element;
	// if the "referenceLine" button is on, draw the reference lines on each viewport
	if(referenceLineButtonPressed === true) {
		updateAllImageDisplayed();
		drawReferenceLine(element);
	}

	// show the element in current viewport which is chosen with a green border
	selectedViewportMarked(elementChoosed);
	if (clickedSeries === -1 || loadedIndex[index] === clickedSeries || changgeSeriesByIndex === -1) {
		return;
	}

	if(loadedIndex[index] != clickedSeries){
		wheelInstanceNum[index] = 0;
	}
	loadedIndex[index] = clickedSeries;

	var curImageIDs = [];
	// load images 找到序列中的所有影像
	if(getDicomButtonPressed){
		loadImages(hosturl, serverURL, studyUID, seriesArray[changgeSeriesByIndex], curImageIDs,
			'dicom');
	} else {
		loadImages(hosturl, serverURL, studyUID, seriesArray[changgeSeriesByIndex], curImageIDs,
			imageType);
	}

	var stack = {
		currentImageIdIndex : 0,
		imageIds : curImageIDs
	};

	$('#modalProgressGlobal').modal('show');

	cornerstone
		.loadAndCacheImage(curImageIDs[0])
		.then(
			function(image) {

				// 开启鼠标操作的功能
				if (isDesktop === true) {
					// 鼠标按下去滑动时间
					cornerstoneTools.mouseInput.enable(element);
				}

				// 开启手机的手势操作功能
				if (isMobile === true) {
					cornerstoneTools.touchInput.enable(element);
				}

				// display this image
				cornerstone.displayImage(element, image);

				// set the stack as tool state
				cornerstoneTools.addStackStateManager(element, [ 'stack' ]);
				cornerstoneTools.addToolState(element, 'stack', stack);

				if (isDesktop === true) {
					//				cornerstoneTools.wwwc.activate(element, 1); // ww/wc
					cornerstoneTools.pan.activate(element, 2); // pan
					cornerstoneTools.zoom.activate(element, 4); // zoom
				}

				if (isMobile === true) {
					cornerstoneTools.stackScrollTouchDrag.activate(element);
				}

				// add synchronizer
				var curGroupIndex = groupIndex[index];
				synchronizers[curGroupIndex].remove(element);
				curGroupIndex = groupIndex[clickedSeries];
				synchronizers[curGroupIndex].add(element);
				groupIndex[index] = groupIndex[clickedSeries];

				triggerResize();
				$('#modalProgressGlobal').modal('hide');

				var newImageId = getDicom(element);
					cornerstone.loadAndCacheImage(newImageId).then(function(image){

						globalWL[index] = image.windowCenter;
						globalWW[index] = image.windowWidth;
						initialWL[index] = globalWL[index];
						initialWW[index] = globalWW[index];

						if(contrastButtonPressed){
							cornerstone.displayImage(element, image);
							var viewport = cornerstone.getEnabledElement(element).viewport;
							viewport.voi.windowCenter = image.windowCenter;
							viewport.voi.windowWidth = image.windowWidth;
							cornerstone.setViewport(element,viewport);
							triggerResize();
						}
				});
			});

	// TODO
	var	displayText = imageInfo.patientname + (imageInfo.patientname!=""?'<br/>':"")
		+ imageInfo.patientid + (imageInfo.patientid!=""?'<br/>':"");
	if (imageInfo.sex == 0) {
		displayText += 'M' + '<br/>';
	} else {
		displayText += 'F' + '<br/>';
	}
	displayText += imageInfo.institutionname + (imageInfo.institutionname!=""?'<br/>':"")
		+ imageInfo.studydescription + (imageInfo.studydescription!=""?'<br/>':"")
		+ series[changgeSeriesByIndex].seriesDescription + (series[changgeSeriesByIndex].seriesDescription!=""?'<br/>':"")
		+ (imageInfo.birthday!=""?'出生日期：':"") + imageInfo.birthday + (imageInfo.birthday!=""?'<br/>':"")
		+ (imageInfo.studydate!=""?'拍摄日期：：':"") + imageInfo.studydate;
	$('#mrbottomright' + index).html(displayText);
	// TODO

	var viewport = cornerstone.getViewport(element);

	// traverse the current series for the current instance ----------------------------------------- started by TanQilu
	var instanceNum;
	for(var i = 0; i < curImageIDs.length; i++){
		var startIndex = curImageIDs[i].indexOf('object')+7;
		var endIndex = curImageIDs[i].indexOf('&rows');
		if(curImageIDs[i].substring(startIndex,endIndex) == seriesArray[clickedSeries].instance[i].sopIUID){
			instanceNum = seriesArray[clickedSeries].instance[i].instanceNumber;
			break;
		}
	}
	// ------------------------------------------------------------------------------------------------- ended by TanQilu

	var displayTextL = 'Img：' + (instanceNum+1) + '/'
		+ series[changgeSeriesByIndex].numberOfInstances + '<br/>' + 'WW：'
		+ Math.round(viewport.voi.windowWidth) + '&nbsp&nbsp'
		+ 'WL：' + Math.round(viewport.voi.windowCenter) + '<br/>'
		+ 'Zoom：' + viewport.scale.toFixed(2) + '<br/>Loc：' + parseFloat(locations[changgeSeriesByIndex]).toFixed(2)
		+ '<br/>Thick：' +  parseFloat(thickness[changgeSeriesByIndex]).toFixed(2);

	$('#mrbottomleft' + index).html(displayTextL);

	changgeSeriesByIndex = -1;
}

//used to get the dicom image of the current jpg ------------------------------ Updated by TanQilu
function getDicom(element){
	var eElement = cornerstone.getEnabledElement(element);
	if(eElement.image.imageId.indexOf( "dicomweb") == -1){
		// convert current imageId to one from which you can achieve the dicom image
		eElement.image.imageId = 'dicomweb:' + eElement.image.imageId + '&contentType=application%2Fdicom' ;
	}
	return eElement.image.imageId;
}

function changeTable() {

	var divs = $("#series");
	var trs = divs[0].getElementsByTagName("tr");
	var len = trs.length;
	for (var i = 0; i < len; i++) {
		trs[i].onclick = function() {
			for (var j = 0; j < len; j++) {
				trs[j].style.backgroundColor = "#000";
			}
			this.style.backgroundColor = "#303030 ";
		};
	}

}

function notifyConfigure() {
	humane.timeout = 4000;
	humane.addnCls = 'humane-libnotify-info';
}

// 设置阅片下的进度条
function selectImage(event) {
	for (var x = 0; x < iWindowHNum; x++) {
		for (var y = 0; y < iWindowVNum; y++) {

			var imageDivId = "image" + x.toString() + y.toString();
			var element = $('#' + imageDivId).get(0);

			if (element === undefined) {
				continue;
			}

			// Get the range input value
			var newImageIdIndex = parseInt(event.currentTarget.value, 10);

			// Get the stack data
			var stackToolDataSource = cornerstoneTools.getToolState(element,
				'stack');
			if (stackToolDataSource === undefined) {
				return;
			}
			var stackData = stackToolDataSource.data[0];

			// Switch images, if necessary
			if (newImageIdIndex !== stackData.currentImageIdIndex
				&& stackData.imageIds[newImageIdIndex] !== undefined) {
				cornerstone.loadAndCacheImage(
					stackData.imageIds[newImageIdIndex]).then(
					function(image) {
						var viewport = cornerstone.getViewport(element);
						stackData.currentImageIdIndex = newImageIdIndex;
						cornerstone.displayImage(element, image, viewport);
					});
			}

		}

	}

}

function selectNewImage(newIndex) {

	for (var x = 0; x < iWindowHNum; x++) {
		for (var y = 0; y < iWindowVNum; y++) {

			var imageDivId = "image" + x.toString() + y.toString();
			var element = $('#' + imageDivId).get(0);

			if (element === undefined) {
				continue;
			}

			// Get the range input value
			var newImageIdIndex = parseInt(newIndex, 10);

			// Get the stack data
			var stackToolDataSource = cornerstoneTools.getToolState(element,
				'stack');
			if (stackToolDataSource === undefined) {
				return;
			}
			var stackData = stackToolDataSource.data[0];

			// Switch images, if necessary
			if (newImageIdIndex !== stackData.currentImageIdIndex
				&& stackData.imageIds[newImageIdIndex] !== undefined) {
				cornerstone.loadAndCacheImage(
					stackData.imageIds[newImageIdIndex]).then(
					function(image) {
						var viewport = cornerstone.getViewport(element);
						stackData.currentImageIdIndex = newImageIdIndex;
						cornerstone.displayImage(element, image, viewport);
					});

			}
		}
	}
}

// image not found for image tag
function imageNotfound() {
	var img = event.srcElement;
	img.src = "../img/BK_UnsportedFormat.png";
	img.onerror = null; // 控制不要一直跳动
}

function cancelBindKey() {
	jQuery(document).unbind('keydown.1');
	jQuery(document).unbind('keydown.2');
	jQuery(document).unbind('keydown.3');
	jQuery(document).unbind('keydown.4');
	jQuery(document).unbind('keydown.5');
	jQuery(document).unbind('keydown.home');
	jQuery(document).unbind('keydown.end');
	jQuery(document).unbind('keydown.pageup');
	jQuery(document).unbind('keydown.left');
	jQuery(document).unbind('keydown.up');
	jQuery(document).unbind('keydown.right');
	jQuery(document).unbind('keydown.down');
	jQuery(document).unbind('keydown.R');
	$("#enableWindowLevelTool").unbind("click");
	$("#pan").unbind("click");
	$("#zoom").unbind("click");
	$("#RotateLeft").unbind("click");
	$("#RotateRight").unbind("click");
	$("#hFlip").unbind("click");
	$("#vFlip").unbind("click");
	$("#reset").unbind("click");
	$("#enableLength").unbind("click");
	$("#probe").unbind("click");
	$("#circleroi").unbind("click");
	$("#rectangleroi").unbind("click");
	$("#angle").unbind("click");
	$("#ShowAnnotation").unbind("click");
	$("#UnShowAnnotation").unbind("click");
	$("#invert").unbind("click");
	$("#WindowLevelHead").unbind("click");
	$("#WindowLevelLung").unbind("click");
	$("#WindowLevelChest").unbind("click");
	$("#WindowLevelAbdomen").unbind("click");
	$("#WindowLevelBone").unbind("click");
}

function goBack() {
	if (null == image2askid || '' == image2askid || 'null' == image2askid) {
		window.history.go(-1);
	} else {
		window.history.go(-2);
	}
}

function parseMessageData(data) {
	try {

		var message = JSON.parse(data);
		return message;
	} catch (e) {
		humane.log("解析数据出错");
		return false;
	}
}

// Distinguish the gourp index for synchronize the viewers
function distinguishGroup() {

	groupIndex[0] = 0;

	for (var i = 1; i < iSeriesNum; i++) {
		if (thickness[i] == thickness[0]
			&& Math.abs(locations[i] - locations[0]) < 0.35
			&& orientation[i] == orientation[0]) {
			groupIndex[i] = groupNum;
		} else {
			groupIndex[i] = groupNum + 1;
		}
	}

	groupNum++;

	for (var i = 1; i < iSeriesNum; i++) {
		if (groupIndex[i] == groupNum) {
			for (var j = i + 1; j < iSeriesNum; j++) {
				if (groupIndex[j] == groupNum) {
					if (thickness[i] == thickness[j]
						&& Math.abs(locations[i] - locations[j]) < 0.35
						&& orientation[i] == orientation[j]) {
						groupIndex[j] = groupNum;
					} else {
						groupIndex[j] = groupNum + 1;
					}
				}
			}
			groupNum++;
		}
	}
	groupNum--;

	var totalGroupNumber = 0;
	for (var i = 0; i < groupIndex.length; i++) {
		if (groupIndex[i] > totalGroupNumber) {
			totalGroupNumber = groupIndex[i] + 1;
		}
	}

	totalGroupNumber++;
	for (var i = 0; i < totalGroupNumber; i++) {
		synchronizers[i] = new cornerstoneTools.Synchronizer(
			"CornerstoneNewImage",
			cornerstoneTools.stackImageIndexSynchronizer);
	}
}


//renumber the instances of every series -----------------------------------Updated by TanQilu
function renumberInstances(){
	for(var i = 0; i < seriesArray.length; i++ ){
		for(var j = 0; j < seriesArray[i].instance.length; j++){
			seriesArray[i].instance[j].instanceNumber = j;
		}
	}
}

//This function is used to display the hint when relevant button is pressed ------Updated by TanQilu
function loadButtonHint() {
	//$("#grid").click(function(){humane.log("多窗口",{timeout : 1000})});
	$("#enableWindowLevelTool").click(function () {
		console.log("humane");
		humane.log("点击鼠标左键，然后滑动，调整窗宽/窗位", {timeout: 1000})
	});
	$("#pan").click(function () {
		console.log("humane");
		humane.log("点击鼠标左键，然后滑动，调整图像位置", {timeout: 1000})
	});
	$("#zoom").click(function () {
		console.log("humane");
		humane.log("滑动，图像放大/缩小", {timeout: 1000})
	});
	$("#RotateLeft").click(function () {
		console.log("humane");
		humane.log("影像左旋转", {timeout: 1000})
	});
	$("#RotateRight").click(function () {
		console.log("humane");
		humane.log("影像右旋转", {timeout: 1000})
	});
	$("#hFlip").click(function () {
		console.log("humane");
		humane.log("影像左右翻转", {timeout: 1000})
	});
	$("#vFlip").click(function () {
		console.log("humane");
		humane.log("影像上下翻转", {timeout: 1000})
	});
	$("#reset").click(function () {
		console.log("humane");
		humane.log("重置影像的位置", {timeout: 1000})
	});
	$("#enableLength").click(function () {
		console.log("humane");
		humane.log("长度测量", {timeout: 1000})
	});
	$("#probe").click(function () {
		console.log("humane");
		humane.log("CT值测量", {timeout: 1000})
	});
	$("#angle").click(function () {
		console.log("humane");
		humane.log("角度测量", {timeout: 1000})
	});
	$("#ShowAnnotation").click(function () {
		console.log("humane");
		humane.log("显示所有的标记", {timeout: 1000})
	});
	$("#UnShowAnnotation").click(function () {
		console.log("humane");
		humane.log("关闭所有的标记", {timeout: 1000})
	});
	$('#wwwc').click(function () {
		console.log("humane");
		humane.log("局部调节窗宽/窗位", {timeout: 1000})
	});
	$("#WindowLevelHead").click(function () {
		console.log("humane");
		humane.log("头颈部 窗宽/窗位=80/35", {timeout: 1000})
	});
	$("#WindowLevelLung").click(function () {
		console.log("humane");
		humane.log("肺部 窗宽/窗位=1500/-500", {timeout: 1000})
	});
	$("#WindowLevelChest").click(function () {
		console.log("humane");
		humane.log("胸腔 窗宽/窗位=500/50", {timeout: 1000})
	});
	$("#WindowLevelAbdomen").click(function () {
		console.log("humane");
		humane.log("腹部 窗宽/窗位=350/50", {timeout: 1000})
	});
	$("#WindowLevelBone").click(function () {
		console.log("humane");
		humane.log("骨 窗宽/窗位=300/1500", {timeout: 1000})
	});
	//$("#autoPlay")              .click(function(){console.log("humane");humane.log("影像自动播放",{timeout : 1000})});
	$("#invert").click(function () {
		console.log("humane");
		humane.log("影像对比度", {timeout: 1000})
	});
	$("#circleroi").click(function () {
		console.log("humane");
		humane.log("椭圆框", {timeout: 1000})
	});
	//$("#threeViews")              .click(function(){console.log("humane");humane.log("三视图",{timeout : 1000})});
	$("#getDicom").click(function () {
		if (imageType == 'dicom') {
			humane.log("获取DICOM原片", {timeout: 1000})
		} else if (imageType == 'jpg') {
			humane.log("获取jpg", {timeout: 1000})
		}
	});
}

function imageSaveAs(){
	var filename = '下载'
	if(elementChoosed === ''){
		var element = $('#image00').get(0);
		cornerstoneTools.saveAs(element, filename);
	}else{
		cornerstoneTools.saveAs(elementChoosed, filename);
	}
	// recoverButtonColor();
	// $('#saveImg').css('background-color','gray');
	// clearIconsColor('saveImg');
	// $("#imageSaveAs").modal('hide');
	// var filename = $("#imageSaveAsName").val();
	// if(elementChoosed === ''){
	// 	var element = $('#image00').get(0);
	// 	cornerstoneTools.saveAs(element, filename);
	// }else{
	// 	cornerstoneTools.saveAs(elementChoosed, filename);
	// }
}

function resizeSeriesDiv(){
	var seriesDivHeight = $('#imageContainer').height();
	var seriesDivWidth = $('#imageContainer').width();
	var clientWidth = document.body.clientWidth;
	var clientHeight = document.body.clientHeight;
	if(clientWidth > clientHeight){
		$('#series').css("height", seriesDivHeight.toString() + 'px');
	}else{
		$('#seriesList').css("width", seriesDivWidth.toString() + 'px');
	}
}

// this function is used to select the next image
// maintaining current window width and center -------------- Updated by TanQilu
function readjustInstanceWWWL(index, element){
//	$('#modalProgressGlobal').modal('show');
	var curDiv = element;
	var curElement = cornerstone.getEnabledElement(curDiv);

	var curImageIDs = [];

	// find the row and column indexes of current element(from 1 not 0)
	var eleRowIndex = element.id.substring(
		element.id.indexOf('image')+5,
		element.id.indexOf('image')+6);
	var eleColumnIndex = element.id.substring(
		element.id.indexOf('image')+6);
	eleRowIndex = parseInt(eleRowIndex);
	eleColumnIndex = parseInt(eleColumnIndex);

	// the image window number
	var eleIndex  = 0;
	if ('' != sort && 1 == iWindowVNum && 1 == iWindowHNum) {
		eleIndex = parseInt(sort);
	} else {
		eleIndex = eleRowIndex*iWindowVNum+eleColumnIndex;
	}

	// the series number
	var eleImgIndex = 0;
	if(iWindowHNum*iWindowVNum==1){
		eleImgIndex = sort;
	} else {
		eleImgIndex = loadedIndex[eleIndex]==-1 ? eleIndex : loadedIndex[eleIndex];
	}

	if(getDicomButtonPressed){
		loadImages(hosturl, serverURL, studyUID, seriesArray[eleImgIndex], curImageIDs,'dicom');
	} else {
		loadImages(hosturl, serverURL, studyUID, seriesArray[eleImgIndex], curImageIDs,imageType);

		if(globalWW[eleIndex]!=undefined && globalWL[eleIndex]!=undefined){
			curImageIDs[index] = curImageIDs[index] +
				'&windowWidth=' + globalWW[eleIndex].toString() +
				'&windowCenter=' + globalWL[eleIndex].toString();
		}
	}

	cornerstone.loadAndCacheImage(curImageIDs[index]).then( function(image){
		if(isDesktop){
			var imgIndex = getImgIndex(undefined,image);
			var elementIdx = 0;
			if(iWindowHNum*iWindowVNum != 1){
				for(var i=0; i<loadedIndex.length; i++){
					if(imgIndex.series == loadedIndex[i]){
						elementIdx = i;
						break;
					}
				}
				if(i == loadedIndex.length){
					elementIdx = imgIndex.series;
				}
			}
		}

		if(isMobile || imgIndex.instance == wheelInstanceNum[elementIdx]){
			cornerstone.displayImage(curDiv,image);
			var viewport = curElement.viewport;

			if(getDicomButtonPressed === false){
				viewport.voi.windowCenter = image.windowCenter;
				viewport.voi.windowWidth = image.windowWidth;
				// if(imageScale[eleRowIndex*iWindowVNum+eleColumnIndex] != undefined){
				// 	viewport.scale = parseFloat(imageScale[eleRowIndex*iWindowVNum+eleColumnIndex]);
				// }
			}

			cornerstone.setViewport(curDiv,viewport);
			// $('#modalProgressGlobal').modal('hide');
			if(image.data == undefined){ // JPG
				cornerstoneTools.probe.disable(element);
				cornerstoneTools.rectangleRoi.disable(element);
				cornerstoneTools.ellipticalRoi.disable(element);
				cornerstoneTools.simpleAngle.disable(element);
				cornerstoneTools.lengthTouch.disable(element);
			}
		}
	});
}

function selectedViewportMarked(element) {
	for(var i = 0; i < iWindowHNum; i++) {
		for(var j = 0; j < iWindowVNum; j++) {
			$('#image' + i.toString() + j.toString()).css('border','1px solid #454444');
			$('#image' + i.toString() + j.toString()).css('border-color','#000');
		}
	}
	var curElementId = element.id;
	$('#' + curElementId).css('border-color','springgreen');
	if(element == '') {
		$('#image00').css('border-color','springgreen');
	}
}



function updateAllImageDisplayed(){
	for(var i=0; i<iWindowHNum; i++){
		for(var j=0; j<iWindowVNum; j++){
			if(i*iWindowVNum+j >= loadedIndex.length){
				break;
			}
			var curElement = $('#image' + i.toString() + j.toString()).get(0);
			cornerstone.updateImage(curElement);
		}
	}
}

// inverse matrix ------Updated by TanQilu
function inverseMatrix(arr){//正确
	//求矩阵的逆
	arrIS=new Array(arr.length);//最大元素的行号
	arrJS=new Array(arr.length);//最大元素的列号
	f=1;fDet=1;
	for(k=0;k<arr.length;k++){
		//第一步 -- 全选主元
		arrMax=0;
		for(i=k;i<arr.length;i++){
			for(j=k;j<arr.length;j++){
				f=Math.abs(arr[i][j]);
				if(f>arrMax){
					arrMax=f;
					arrIS[k]=i;
					arrJS[k]=j;
				}
			}
		}
		if(Math.abs(arrMax)<0.000001)return arr;
		if (arrIS[k] != k) {
			f = -f;
			for(kk=0;kk<arr.length;kk++){
				temp=swap([arr[k][kk],arr[arrIS[k]][kk]]);
				arr[k][kk]=temp[0];
				arr[arrIS[k]][kk]=temp[1];
			}
		}
		if (arrJS[k] != k) {
			f = -f;
			for(kk=0;kk<arr.length;kk++){
				temp=swap([arr[kk][k],arr[kk][arrJS[k]]]);
				arr[kk][k]=temp[0];
				arr[kk][arrJS[k]]=temp[1];
			}
		}
		// 计算行列值
		fDet *= arr[k][k];
		// 计算逆矩阵
		arr[k][k]= 1/ arr[k][k];
		// 第三步
		for (j=0;j<arr.length;j++) {
			if (j!=k) arr[k][j]*= arr[k][k];
		}
		// 第四步
		for (i=0;i<arr.length;i++) {
			if(i!=k){
				for (j=0;j<arr.length;j++) {
					if(j!=k) arr[i][j]=arr[i][j]- arr[i][k]*arr[k][j];
				}
			}
		}
		// 第五步
		for (i=0;i<arr.length;i++) {
			if (i!=k)arr[i][k]*=-arr[k][k];
		}
		//--end of k=0,..,n-1
	}
	//最后恢复
	for (k = arr.length-1; k >= 0; k --) {
		if (arrJS[k] != k) {
			for(kk=0;kk<arr.length;kk++){
				temp=swap([arr[k][kk],arr[arrJS[k]][kk]]);
				arr[k][kk]=temp[0];
				arr[arrJS[k]][kk]=temp[1];
			}
		}
		if (arrIS[k] != k) {
			for(kk=0;kk<arr.length;kk++){
				temp=swap([arr[kk][k],arr[kk][arrIS[k]]]);
				arr[kk][k]=temp[0];
				arr[kk][arrIS[k]]=temp[1];
			}
		}
	}
	return arr;
}
function swap(arr){//正确
	temp=arr[0];
	arr[0]=arr[1];
	arr[1]=temp;
	return arr;
}

//This function is used to display plotting scales in each viewport -------------- Updated by TanQilu
function plottingScale(element){
	try{
		// get the series number and instance number
		var imgIndex = getImgIndex(element);

		// get the series number and instance number
		var instanceNum = imgIndex.instance;
		var seriesNum = imgIndex.series;

		// achieve the image information
//		var row = cornerstone.getImage(element).rows;
//		var column = cornerstone.getImage(element).columns;
		var row = parseFloat(tagArray[seriesNum][instanceNum].rows);
		var column = parseFloat(tagArray[seriesNum][instanceNum].columns);

		var rowSpacing = parseFloat(tagArray[seriesNum][instanceNum].pixelSpacing.split('\\')[0]);
		var columnSpacing = parseFloat(tagArray[seriesNum][instanceNum].pixelSpacing.split('\\')[1]);
//		var rowSpacing = cornerstone.getImage(element).rowPixelSpacing;
//		var columnSpacing = cornerstone.getImage(element).columnPixelSpacing;

		// 如果是JPG格式，校准坐标系
		var rowScale = 1;
		var columnScale = 1;
		if(cornerstone.getImage(element).data == undefined){ // JPG
			var jpgRow = cornerstone.getImage(element).rows;
			var jpgColumn = cornerstone.getImage(element).columns;
			rowScale = row/jpgRow;
			columnScale = column/jpgColumn;
		}

		// the width of the scale div
		var zoom = cornerstone.getEnabledElement(element).viewport.scale;
		var len = column/columnScale * zoom;
		// the left margin of the scale div
		var viewportWidth = $('#'+element.id).find('canvas').width();
		var sideMargin = parseInt((viewportWidth-len)/2)>0 ? parseInt((viewportWidth-len)/2) : 0;

		$('#scaleDiv'+element.id.substring(5)).remove();

		// scale div
		var scaleDiv = $('<div></div>');
		scaleDiv.attr('id','scaleDiv'+element.id.substring(5));
		scaleDiv.attr('style','position: absolute; bottom: 6px; left:'+sideMargin+'px; right:'+sideMargin+'px; height: 40px;');
		scaleDiv.appendTo($('#'+element.id));

		// scale canvas, in which we plot the scale
		var scale = $('<canvas></canvas>');
		scale.attr('id','scale'+element.id.substring(5));
		scale.attr('width',(len+40<viewportWidth ? len+40 : viewportWidth).toString()+'px');
		scale.attr('height','40px');
		scale.appendTo($('#scaleDiv'+element.id.substring(5)));

		// plot the scale
		var canvas = document.getElementById('scale'+element.id.substring(5));
		var context = canvas.getContext("2d");
		context.beginPath();
		context.lineWidth = 2;
		context.strokeStyle = 'white';
		context.moveTo(0,40);
		context.lineTo(len-1,40);

		// define the text style written in the canvas
		cornerstoneTools.textStyle.setFont('12px Arial');
		var font = cornerstoneTools.textStyle.getFont();
		context.font = font;
		cornerstoneTools.drawTextBox(context,'cm',len+15,40-5,'white');

		// draw the scale marks
		var i = 0, time = 0;
		while(i<len){
			context.moveTo(i, 40);
			context.lineTo(i, 40-5);

			cornerstoneTools.drawTextBox(context,(5*time).toString(),i,40-5,'white');

			i += 50/(columnSpacing*columnScale)*zoom;
			time++;
		}

		context.stroke();

		// 竖屏状态下调整底部的导航栏宽度
		if(isDesktop || clientWidth < clientHeight){
			$(' #seriesList').css('width',$(' #imageContainer').width().toString());
		}

	} catch(err){
		// 上一段行代码有时出bug，但尚未找到问题所在，先用try catch语句临时顶替下，保证程序能够正常运行
	}
}

// get the series number and instance number of the element---------------- Updated by TanQilu
function getImgIndex(element/*optional*/,image/*optional*/){
	var imgNum = '';
	var instanceNum = 0;
	var startIdx = 0;
	var endIdx = 0;
	var seriesId = '';
	var seriesNum = '';

	if(element != undefined){
		// find the instanceNum
		imgNum = element.children[2].innerHTML.split('<br>')[0].split('：')[1];
		instanceNum = parseInt(imgNum.split('/')[0])-1;

		// find the seriesId
		startIdx = cornerstone.getImage(element).imageId.indexOf('series') + 7;
		endIdx = cornerstone.getImage(element).imageId.indexOf('&object');
		seriesId = cornerstone.getImage(element).imageId.substring(startIdx,endIdx);
	}

	if(image != undefined){
		// find the seriesId
		startIdx = image.imageId.indexOf('series') + 7;
		endIdx = image.imageId.indexOf('&object');
		seriesId = image.imageId.substring(startIdx,endIdx);
	}

	// find the seriesNum
	for(var i = 0; i < seriesArray.length; i++){
		if(seriesId == seriesArray[i].seriesUID){
			seriesNum = i;
			break;
		}
	}

	if(image != undefined){
		// find the instanceNum this image
		var idStart = image.imageId.indexOf('object=')+7;
		var idEnd = image.imageId.indexOf('&rows');
		var objectId = image.imageId.substring(idStart,idEnd);

		for(var i=0; i<seriesArray[seriesNum].instance.length; i++){
			if(objectId == seriesArray[seriesNum].instance[i].sopIUID){
				instanceNum = i;
				break;
			}
		}
	}

	var imgIndex = {
		instance: instanceNum,
		series:   seriesNum
	}
	return imgIndex;
}

// this function is used to sort the "tags" array, in order to unify the structure
// of "tagArray" and "seriesArray" ---------------------------------- Updated by TanQilu
function sortTags(){
	// for each element in tags, judge the position in the "tagArray" it should be in
	for(var i = 0; i < tags.length; i++){
		// to confirm the first index of the element (its series number)
		for(var j = 0; j < seriesArray.length; j++){
			if(tags[i].seriesIuid == seriesArray[j].seriesUID){
				// to confirm the second index of the element (its instance number)
				for(var k = 0; k < seriesArray[j].instance.length; k++){
					if(tags[i].sopIuid == seriesArray[j].instance[k].sopIUID){
						tagArray[j][k] = tags[i];
						j = seriesArray.length;
						break;
					}
				}
			}
		}
	}
}

//used to get the dicom image of the current jpg ------------------------------ Updated by TanQilu
function getDicom(element){
	var eElement = cornerstone.getEnabledElement(element);
	if(eElement.image.imageId.indexOf( "dicomweb") == -1){
		// convert current imageId to one from which you can achieve the dicom image
		eElement.image.imageId = 'dicomweb:' + eElement.image.imageId + '&contentType=application%2Fdicom' ;
	}
	return eElement.image.imageId;
}

function getDicomClick(){
	isGetDicomButtonPressed = true;
	recoverButtonColor();
	$('#getDicom').css('background-color','gray');
	if(getDicomButtonPressed){
		getDicomButtonPressed = false;
	} else {
		getDicomButtonPressed = true;
		imageType = 'jpg';
	}
	showSeries(iWindowVNum, iWindowHNum);
	if($('#getDicom').find('span').html() == 'JPG'){
		$('#getDicom').find('span').html('DCM');
	} else {
		$('#getDicom').find('span').html('JPG');
	}
}
//@ sourceURL=imageShow.js

/*
$('#navToggle').click(function(){
	console.log("navtoggle");
	resizeCanvas();
});*/

/*$('.navbar-header').click(function(){
	console.log("navbar-header");
	resizeCanvas();
});*/
